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

Mark Lanzo lanzo at wgate.UUCP
Mon Oct 1 23:36:47 AEST 1990


In article <Sep.30.21.09.46.1990.2881 at romulus.rutgers.edu> mef at romulus.rutgers.edu (Marc Fiuczynski) writes:
>
>For my Operating System Design class we had to write some trivial 
>programs using the fork() and wait() commands.  The teaching assistant
>came across an interesting problem.  After compiling the following:
>
> 
>#include <stdio.h>
>
>main ()
>{
>	int pid = 1;
>	printf("Hello\n");
>	pid=fork();
>	if(pid==0){
>		printf("World\n");
>	}
>}
>

[ ... Description of how output gets repeated twice in file if 
stdout is redirected ... ]

I believe your problem is that you are not flushing your open file buffers
before doing your fork() call.  Remember that the "stdio" package is a
buffered I/O package layered on top of the level-1 I/O calls (like "open",
"close", "read", and "write");  hence, some of the data you are writing
isn't really being written immediately, but is instead deferred until
a buffer gets filled.

Hence, your are doing a 'printf("Hello\n")' which is causing the character
string to be written into an anonymous buffer hanging off of the FILE
structure.  When the buffer is filled, the stdio package will do something
which pretty much amounts to an 'fflush(stdout)'.

What is happening in your case is this:

   1)  You print the characters "Hello\n" into a buffer.
   2)  You fork the process.  Both copies of the program still have
       this data in their buffer!
   3)  Both copies continue to run, eventually flushing their buffers.
       The order in which the output from the parent and child processes
       gets intermingled is undefined.

The thing which really confuses you is that you don't see this behavior
when you *aren't* redirecting your output.  It does exactly what you
expected.  This is because the stdio package normally uses a "line buffered"
or "unbuffered" mode of I/O when writing to a terminal and hence your
output does get flushed prior to the 'fork()' call.

The quick cure?  Flush the output stream(s):

	printf("Hello\n");
	fflush(stdout);
	pid = fork();

Your system may have a better means for flushing buffers, like 
'fflushall()' [ours doesn't].
-- 
Mark Lanzo                      | Wandel & Goltermann Technologies, Inc.
uunet!wgate!lanzo               | 1030 Swabia Court, Research Triangle Park
lanzo at wgate.wgate.com ??        | North Carolina 27709-3585
                                | Phone: (919) 941-5730  FAX: (919) 941-5751



More information about the Comp.lang.c mailing list