Question

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

    printf("c");
    exit(0);
}

The above code asks what are the possible outputs?

I find that, acbc, abcc, bacc but answer includes bcac. How can bcac be an answer? Is parent process exits before child process created or sth. else? I confused, any explanations are welcome.

Thnx.

Was it helpful?

Solution

The only guarantee is that waitpid won't return (unless it's interrupted) until the child's status information is available. As soon as you call exit(0), the 0 is available. So waitpid can return before the child's output is flushed.

POSIX says: "The wait() function shall suspend execution of the calling thread until status information for one of the terminated child processes of the calling process is available, or until delivery of a signal whose action is either to execute a signal-catching function or to terminate the process." (It also says waitpid is identical in this respect.)

I don't know of any actual platform where this happens and can only imagine it happening on an OS that emulates POSIX in user space and thus has some user space code to signal the parent that the child is terminating rather than using its actual termination to signal the parent. But it's permitted by the standards.

This is really obscure and I wonder if this is the expected rationale for that sequence. I can think of no other.

OTHER TIPS

The answer is 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top