Why does this code fragment only produce the letters "XUVUV"? I would think "UXUVV" would also be a possibility, but I never get that output.
if (fork() == 0){
printf("X");
}
printf("U");
wait(NULL);
printf("V");
Why does this code fragment only produce the letters "XUVUV"? I would think "UXUVV" would also be a possibility, but I never get that output.
if (fork() == 0){
printf("X");
}
printf("U");
wait(NULL);
printf("V");
Copyright © 2021 Jogjafile Inc.
There are no newlines printed; therefore, no output appears until the process terminates.
The child process adds
Xto its buffer; the parent does not print anX. The child then addsUto its buffer. It waits, but the wait returns immediately; the child has no children to wait for. It addsVto its buffer. It terminates, so theXUVis flushed.Meanwhile, the parent has added
Uto its buffer; it then waits for the child to finish. When the child has finished, theXUVhas been printed. The parent addsVto its buffer and exits; itsUVare flushed to the output.The consequence is that you see
XUVUVevery time.You can't tell whether the child adds its characters to its buffer before or after the parent adds its
Uto its buffer, but you do know the child has completed before the parent adds theV, so the output is determinate unless you do something fancy likesetvbuf(stdout, 0, _IONBF, 0)to make the standard output unbuffered before you do any output operations.If you add newlines to each print operation, things get more complicated; the timing ceases to be determinate.