Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!helios!csseq!randy From: randy@csseq.tamu.edu (Randy Hutson) Newsgroups: comp.lang.c Subject: Re: erroneous "hello" from forked "hello world" process! Keywords: fork(), wait(), Hello World Message-ID: <8661@helios.TAMU.EDU> Date: 1 Oct 90 03:13:49 GMT References: Sender: usenet@helios.TAMU.EDU Organization: Computer Science Department, Texas A&M University Lines: 53 In article mef@romulus.rutgers.edu (Marc Fiuczynski) writes: >#include > >main () >{ > int pid = 1; > printf("Hello\n"); > pid=fork(); > if(pid==0){ > printf("World\n"); > } >} [Marc explains that when the above program is executed and redirected to a file, the expected string "Hello\nWorld\n" is not in the file, but instead either "Hello\nHello\nWorld\n" or "Hello\nWorld\nHello\n".] After a fork, a child process will inherit the stdio buffers of its parent. In your case, printf("Hello\n") was not sufficient to flush the stdio buffer of the parent process, so "Hello\n" was written to a buffer but not to the file. Right after the fork, "Hello\n" was in the stdio buffers of both processes. Then after the child executed printf("World\n"), its buffer contained "Hello\nWorld\n" while the parent's buffer still contained only "Hello\n". The order in which the two processes terminate (with their buffers being flushed) is not defined, hence you sometimes got "Hello\nHello\nWorld\n" (the parent exited first) and other times got "Hello\nWorld\nHello\n" (the child exited first). You will probably get the output you desire if you don't redirect the output of your program. This is because most (at least) terminal drivers are newline buffered, and the '\n' in printf("Hello\n") is sufficient to flush the buffer. In any case, a "correct" version of your program follows with a fflush(stdout) executed right after the first printf: #include main () { printf("Hello\n"); fflush(stdout); pid=fork(); if(pid==0){ printf("World\n"); } } Randy Hutson randy@csseq.tamu.edu