erroneous "hello" from forked "hello world" process!
Randy Hutson
randy at csseq.tamu.edu
Mon Oct 1 13:13:49 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");
> }
>}
[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 <stdio.h>
main ()
{
printf("Hello\n");
fflush(stdout);
pid=fork();
if(pid==0){
printf("World\n");
}
}
Randy Hutson
randy at csseq.tamu.edu
More information about the Comp.lang.c
mailing list