Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!uwm.edu!wuarchive!uunet!munnari.oz.au!goanna!ok From: ok@goanna.cs.rmit.oz.au (Richard A. O'Keefe) Newsgroups: comp.lang.c Subject: Re: erroneous "hello" from forked "hello world" process! Keywords: fork(), wait(), Hello World Message-ID: <3856@goanna.cs.rmit.oz.au> Date: 1 Oct 90 02:17:32 GMT References: Organization: Comp Sci, RMIT, Melbourne, Australia Lines: 29 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"); > } > [Output includes two "Hello"s when redirected to a file.] Engrave this on the tablets of your mind: stdio is BUFFERED! Neither the "Hello\n" nor the "World\n" is being written by either process until the buffer fills or the buffer is flushed when the file is closed at process termination. The processes share a UNIX file descriptor and that descriptor's file pointer, but the stdio buffer is *copied*, not shared. The simplest method is to call setbuf(stdout, (char*)NULL); If you have setvbuf(), setvbuf(stdout, (char*)NULL, _IOLBUF, 0); will flush the buffer after every line, which may suffice. Best of all is to treat shared files as shared resources and interlock them properly, using semaphores or whatever, and fflush when "ownership" of the file passes from one process to another. -- Fixed in the next release.