fork() and redirection

Chris Torek chris at mimsy.umd.edu
Fri Feb 16 23:37:07 AEST 1990


In article <Feb.15.14.14.27.1990.4568 at acdc.rutgers.edu>
andrewsr at acdc.rutgers.edu (Richard L Andrews) writes:
>Why does the fork command start the child process at the point where
>it occurs in the program normally, yet restart the child process when
>the output is redireced to a file?

It does not.

Fork() makes a copy of the program that calls fork().  In all but one
respect (the return value), the copy is identical to the original.

Now, what happens when the original includes a bunch of stuff marked
`write this to stdout sometime soon'?  Surprise, two copies of that
`stuff' get written.  Well, characters printed to stdout go in a buffer
and wait around until a `good' time to get written, so they get copied.
On a `tty' device, every newline is considered a `good' time to write,
so that a program that forks immediately after printing a newline has
no stuff marked `write this soon'; but on any other output file, newlines
are not considered `good' times to write, so that a program that forks
immediately after printing a newline typically prints more than one
newline.

(This is yet another example of how line-buffered output is a mistake.)

In other words, printf() does not mean `print this': it means `remember
to print this eventually'.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at cs.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.unix.questions mailing list