erroneous "hello" from forked "hello world" process!

Richard A. O'Keefe ok at goanna.cs.rmit.oz.au
Mon Oct 1 12:17:32 AEST 1990


In article <Sep.30.21.09.46.1990.2881 at romulus.rutgers.edu>, mef at romulus.rutgers.edu (Marc Fiuczynski) writes:
> #include <stdio.h>
> 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.



More information about the Comp.lang.c mailing list