Path: utzoo!attcan!uunet!mcsun!ukc!edcastle!aiai!richard From: richard@aiai.ed.ac.uk (Richard Tobin) Newsgroups: comp.unix.wizards Subject: Re: Child doing parent's printf ?? Message-ID: <1743@skye.ed.ac.uk> Date: 13 Feb 90 17:15:03 GMT References: <9123.25d6719a@ecs.umass.edu> Reply-To: richard@aiai.UUCP (Richard Tobin) Organization: AIAI, University of Edinburgh, Scotland Lines: 38 >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@uk.ac.ed AI Applications Institute, ARPA: R.Tobin%uk.ac.ed@nsfnet-relay.ac.uk Edinburgh University. UUCP: ...!ukc!ed.ac.uk!R.Tobin