fork() and redirection

Richard L Andrews andrewsr at acdc.rutgers.edu
Fri Feb 16 06:14:32 AEST 1990


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?  (I am using the tsch shell on UNIX).

Example:
--------
Code:
-----
#include <stdio.h>

main(

     printf("This is a test.\n");
     printf("Statement 2 in main.\n");
     if (fork() == 0) {
          printf("Child statement 1\n");
          printf("Child statement 2\n");
     } else {
          printf("Parent statement 3\n");
          printf("Parent statement 4\n");
     }
}

when output to terminal:
------------------------
This is a test.
Statement 2 in main.
Parent statement 3
Parent statement 4
Child statement 1
Child statement 2

When piped to a file, the file reads:
-------------------------------------
This is a test.
Statement 2 in main.
Parent statement 3
Parent statement 4
This is a test.
Statement 2 in main.
Child statement 1
Child statement 2


When displayed on the terminal, although the output can be
undetermined, it never prints "This is a test." twice.

Much thanks in advance.
-Rich
-- 
  //   Richard L Andrews II   |"Like any good philosophical discussion, the
\X/ andrewsr at topaz.rutgers.edu| conclusion is left unresolved." -McLaughlin



More information about the Comp.unix.questions mailing list