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

Chris Torek chris at mimsy.umd.edu
Mon Oct 1 17:15:03 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.

fork() and wait() are not part of the C language, so this belongs in
comp.unix.programmer.  I have redirected followups.  (Old-timers may
note that I try to be impartial about all misdirected stuff, not just
MS-DOS stuff).

His TA expects

>	printf("Hello\n");
>	pid=fork();
>	if(pid==0){
>		printf("World\n");
>	}

to produce

>Hello
>World

but instead it produces one of `Hello\nHello\nWorld' or `Hello\nWorld\nHello'.

>Does anyone know what is going on?

Your TA should; he or she should certainly know about the boundaries
between `things in the operating system' and `things not in the
operating system' in order to work with an OS class in the first place.
printf() is part of the C runtime system, *not* the Unix OS; fork()
and wait() are part of the Unix OS, not the C runtime system.  Thus
there is no guarantee about the way the two interact.

In particular, when printing to a `buffered' file the runtime system
buffers (hence the name) the text until it has a `suitable amount' to
write at once.  It then sends it all out with one or more write() system
calls.  Since fork() simply duplicates all the data in the program, it
duplicates any buffered text.  Thus the program above becomes one
process with `Hello\n' buffered, and one with `Hello\nWorld\n' buffered.

The real oddity is not that the word `Hello' is ever duplicated, but
rather that it is sometimes *not* duplicated.  This happens whenever
the string `Hello\n' is written out before the program forks, which
includes whenever the standard output is line buffered or unbuffered.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 405 2750)
Domain:	chris at cs.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list