fork() and redirection

Doug Gwyn gwyn at smoke.BRL.MIL
Fri Feb 16 09:19:11 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?

First, it's not a fork command, it's a fork system call.  Commands are
things you feed to a shell.

Fork does not do what you say it does.  It causes the process to clone
itself and resume executing immediately after the system call in both
processes, the main discernable difference being that the system call
appears to have returned different values in the different processes.
This is unaffected by what the original process's standard output
happens to be.

>Example:
>#include <stdio.h>

Well, there is your problem.  Your printf()s are getting buffered in
your process data space (in effect inside the C library), and that
buffer is part of what is cloned and therefore inherited by both
processes after the fork.  The buffer is automatically flushed by the
stdio package when outputting a new-line to a terminal device, but is
flushed only when the buffer fills up when outputting to a regular
file.  We discussed all this on a couple of recent occasions.  The
solution is to explicitly unvoke fflush() to flush the buffer before
the fork.



More information about the Comp.unix.questions mailing list