Child doing parent's printf ??

Greyham Stoney greyham at hades.OZ
Thu Feb 22 07:22:02 AEST 1990


in article <9123.25d6719a at ecs.umass.edu>, satam at ecs.umass.edu (Kirtikumar Satam, ECE, UMASS Amherst) says:
> 
> 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.

How's this:
	standard output is line-buffered when the output is a terminal, but is
block buffered when the output is a file. Hence, when you run it from a
terminal, stdout is implicitly flushed at the end of each line, and you get
three messages. With output redirected though, the message is still in the
stdout buffer, and get duplicated by the fork. The child then adds it message
to the buffer, which eventually gets flushed at exit().

	Meanwhile, the parent adds its second message too, and they both get
flushed at exit(). Hence:

: Now, the output on tty is
: ----------------------tty output --------------------
: Parent : I am parent with pid 7704		<---- Flushed before the fork()
: Child : I am child of parent 7704 and my pid is 7705
: Parent : My child with pid 7705 died
: ----------------------------------------------------
: 
: ANd when I redirect it is
: ----------------------Redirected-------------------
: Parent : I am parent with pid 7708		<--- from child's buffer
: Child : I am child of parent 7708 and my pid is 7709
: Parent : I am parent with pid 7708		<--- from parent's buffer
: Parent : My child with pid 7709 died
: ----------------------------------------------------

> The above problem can be removed by using fflush(stdout)
> before forking.

Yep, that's your solution. Note that using stderr wont do it either cos it's
not buffered.

							Greyham.
-- 
/*  Greyham Stoney:                            Australia: (02) 428 6476  *
 *     greyham at hades.oz  - Ausonics Pty Ltd, Lane Cove, Sydney, Oz.      *
 * "Beware! Grid Bugs!"  \ Quotes from the Ultimate Video Experience...  *
 * "Nice Try, Timelord!" / Can you identify it? Win absolutely nothing!  */



More information about the Comp.unix.wizards mailing list