Reputation: 29
In studying CSAPP, I encounter the practice: list all of the possible output sequences for the following program:
int main()
{
if(Fork()==0) {
printf("a");
}
else {
printf("b");
waitpid(-1,NULL,0);
}
printf("c");
exit(0);
}
the answer is :acbc abcc bcac bacc;
Why is bcac
correct? The function waitpid()
suspends execution of the calling process until the child process in its wait set terminates. So the parent can't not print c
, until the child process terminate, which means the child prints both a
and c
.
I'm really confused about it. I don't know why bcac
is correct. The parent process should hold or suspend until child terminates.
Upvotes: 2
Views: 731
Reputation: 3157
As Joachim Pileborg suggests, this is a flushing output problem. Just use the following:
int main()
{
if(Fork()==0)
{
printf("a\n");
}
else
{
printf("b\n");
waitpid(-1,NULL,0);
}
printf("c\n");
exit(0);
}
'\n' characters should automatically flush stdout or stderr. You can also use fflush(stdout);
Upvotes: 1