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

Tim Olson tim at proton.amd.com
Tue Oct 2 00:07:47 AEST 1990


In article <Sep.30.21.09.46.1990.2881 at romulus.rutgers.edu> mef at romulus.rutgers.edu (Marc Fiuczynski) writes:

[program performs a printf("Hello\n"), followed by a fork(), then a
printf("World\n"); Marc wonders why "Hello" is printed twice...]

| does anyone know what is going on?   Is there a problem because there are
| two processes output being redirected to the filename or what?  Any help
| with this would be appreciated.  

Here is what is going on:

Your program uses the stdio package to print the output.  This package
performs buffering in order to improve performance, as it is faster to
collect many characters to send to one write() system call, rather
than to perform a system call each time.

For tty output, stdio usually buffers only a line, calling write()
when a newline character is reached.  However, when writing to a file,
it usually buffers more, typically 1K characters (see the BUFSIZ
definition in <stdio.h>).

When you perform the fork() operation, the child process gets an exact
copy of the parent, including all open files, all buffered output,
etc.  Thus, when redirecting standard output to a file, the first
printf("Hello\n") is buffered when the fork() occurs, giving both
parent and child a copy of this buffer.  The parent goes on to
printf("World\n"), while the child simply exits.  In the process of
exiting, all buffered output is flushed.

The order of execution of the two processes is undefined, so the final
output may be either:

Hello			Hello
World		or	Hello
Hello			World


To fix this problem, any buffered output should be flushed before
forking:

include <stdio.h>

main()
{
	printf("Hello\n");
	fflush(stdout);
	fflush(stderr);
	if (fork() == 0) {
		printf("World\n");
	}
}



	-- Tim Olson
	Advanced Micro Devices
	(tim at amd.com)



More information about the Comp.lang.c mailing list