Path: utzoo!utgpu!jarvis.csri.toronto.edu!cs.utexas.edu!wuarchive!udel!haven!mimsy!chris From: chris@mimsy.umd.edu (Chris Torek) Newsgroups: comp.unix.questions Subject: Re: fork() and redirection Message-ID: <22575@mimsy.umd.edu> Date: 16 Feb 90 12:37:07 GMT References: <7638@tank.uchicago.edu> <12137@smoke.BRL.MIL> Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 29 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? 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@cs.umd.edu Path: uunet!mimsy!chris