Path: utzoo!utgpu!jarvis.csri.toronto.edu!cs.utexas.edu!uunet!munnari.oz.au!cluster!ultima!hades!greyham From: greyham@hades.OZ (Greyham Stoney) Newsgroups: comp.unix.wizards Subject: Re: Child doing parent's printf ?? Message-ID: <608@hades.OZ> Date: 21 Feb 90 20:22:02 GMT References: <9123.25d6719a@ecs.umass.edu> Organization: Ausonics Pty Ltd, Sydney, Australia Lines: 44 in article <9123.25d6719a@ecs.umass.edu>, satam@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@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! */