Why does this code with fork() only produce one output?

103 Views Asked by At

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");
1

There are 1 best solutions below

0
On

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 an X. The child then adds U to its buffer. It waits, but the wait returns immediately; the child has no children to wait for. It adds V to its buffer. It terminates, so the XUV is flushed.

Meanwhile, the parent has added U to its buffer; it then waits for the child to finish. When the child has finished, the XUV has been printed. The parent adds V to its buffer and exits; its UV 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 the V, so the output is determinate unless you do something fancy like setvbuf(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.