Child doing parent's printf ??

Richard Tobin richard at aiai.ed.ac.uk
Wed Feb 14 04:15:03 AEST 1990


>I was playing with fork() and wrote the following program. The program
>works as expected when its stdout is tty. But, when I redirect it to
>a file an additional printf comes. Here it is.

Surprise!

When the output is a terminal, it is buffered in the program until a
linefeed is written.  Then it is flushed as if with fflush().

When the output is not to a terminal, it is buffered in the program until
"enough" has been written or until the program exits.  This is because it's
more efficient to do the actual writing in large blocks.  (If this was
done with terminal output, it would be rather confusing.)

When the program forks, the output is still buffered.  Both the child and
the parent get a copy of it, and both flush it when they exit.

>----------------------Redirected-------------------
>Parent : I am parent with pid 7708
>Child : I am child of parent 7708 and my pid is 7709
>Parent : I am parent with pid 7708
>Parent : My child with pid 7709 died
>----------------------------------------------------

>Clearly the third line is being printed by the child.

Actually, the first two lines are printed by the child when it exits,
and the third and fourth by the parent when it exits.

A solution is to flush all output streams before doing a fork().
An alternative if the child does no output is to have the child call
_exit() instead of exit(); this bypasses stdio cleanup.

-- Richard
-- 
Richard Tobin,                       JANET: R.Tobin at uk.ac.ed             
AI Applications Institute,           ARPA:  R.Tobin%uk.ac.ed at nsfnet-relay.ac.uk
Edinburgh University.                UUCP:  ...!ukc!ed.ac.uk!R.Tobin



More information about the Comp.unix.wizards mailing list