fork() and waitpid possible outputs

968 views Asked by At

My textbook gives the following main routine:

int main()
{
if(fork() == 0)
    {
        printf("a");
    }
    else
    {
        printf("b");
        waitpid(-1, NULL, 0);
    }
    printf("c");
    exit(0);
}

It asks what the possible outputs are, and I have found 3:

abcc: The OS chooses the child process to execute first, and prints "a". Then, the OS pauses the child process and resumes the parent process, printing "b". Then the parent must wait until the child is done, and the child prints "c", and finally the parent prints "c".

bacc: The OS chooses the parent process to run first, and prints "b". Then the parent must wait for the child to complete and print "ac". Then the parent prints "c".

acbc: The OS chooses the child to run first until completion, printing "ac". Then the parent runs to completion, printing "bc".

However, there is one more answer listed in the textbook, bcac. I don't understand how this is possible because if b is printed first, then the parent must wait for the child to continue, and print "ac", then the parent would print "c", giving bacc which I've already listed. Is there something I'm missing, or is it correct to say there are only 3 possible outputs?

1

There are 1 answers

0
milktrey On

Don't always trust textbooks...

From the errata:

p. 772, Solution to Practice Problem 8.3. The sequence bcac is not possible. Strike the second to last sentence. The last sentence should be “There are three possible sequences: acbc, abcc, and bacc.” Please see Web Aside ECF:GRAPHS on the Web Aside page for an example of the process graph.