Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!umich!yale!cmcl2!adm!smoke!gwyn From: gwyn@smoke.BRL.MIL (Doug Gwyn) Newsgroups: comp.unix.questions Subject: Re: fork() and redirection Message-ID: <12155@smoke.BRL.MIL> Date: 15 Feb 90 22:19:11 GMT References: <7638@tank.uchicago.edu> <12137@smoke.BRL.MIL> Reply-To: gwyn@brl.arpa (Doug Gwyn) Organization: Ballistic Research Lab (BRL), APG, MD. Lines: 27 In article andrewsr@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 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.