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
X
to its buffer; the parent does not print anX
. The child then addsU
to its buffer. It waits, but the wait returns immediately; the child has no children to wait for. It addsV
to its buffer. It terminates, so theXUV
is flushed.Meanwhile, the parent has added
U
to its buffer; it then waits for the child to finish. When the child has finished, theXUV
has been printed. The parent addsV
to its buffer and exits; itsUV
are flushed to the output.The consequence is that you see
XUVUV
every time.You can't tell whether the child adds its characters to its buffer before or after the parent adds its
U
to 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.