Path: utzoo!attcan!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uwm.edu!rpi!julius.cs.uiuc.edu!apple!netcom!amdcad!mozart.amd.com!proton!tim From: tim@proton.amd.com (Tim Olson) Newsgroups: comp.lang.c Subject: Re: erroneous "hello" from forked "hello world" process! Message-ID: <1990Oct1.140747.20447@mozart.amd.com> Date: 1 Oct 90 14:07:47 GMT References: Sender: usenet@mozart.amd.com (Usenet News) Reply-To: tim@amd.com (Tim Olson) Organization: Advanced Micro Devices, Inc., Austin, Texas Lines: 57 In article mef@romulus.rutgers.edu (Marc Fiuczynski) writes: [program performs a printf("Hello\n"), followed by a fork(), then a printf("World\n"); Marc wonders why "Hello" is printed twice...] | does anyone know what is going on? Is there a problem because there are | two processes output being redirected to the filename or what? Any help | with this would be appreciated. Here is what is going on: Your program uses the stdio package to print the output. This package performs buffering in order to improve performance, as it is faster to collect many characters to send to one write() system call, rather than to perform a system call each time. For tty output, stdio usually buffers only a line, calling write() when a newline character is reached. However, when writing to a file, it usually buffers more, typically 1K characters (see the BUFSIZ definition in ). When you perform the fork() operation, the child process gets an exact copy of the parent, including all open files, all buffered output, etc. Thus, when redirecting standard output to a file, the first printf("Hello\n") is buffered when the fork() occurs, giving both parent and child a copy of this buffer. The parent goes on to printf("World\n"), while the child simply exits. In the process of exiting, all buffered output is flushed. The order of execution of the two processes is undefined, so the final output may be either: Hello Hello World or Hello Hello World To fix this problem, any buffered output should be flushed before forking: include main() { printf("Hello\n"); fflush(stdout); fflush(stderr); if (fork() == 0) { printf("World\n"); } } -- Tim Olson Advanced Micro Devices (tim@amd.com)