Xref: utzoo comp.lang.c:32391 comp.unix.programmer:149 Path: utzoo!attcan!utgpu!news-server.csri.toronto.edu!mailrus!wuarchive!udel!haven!mimsy!chris From: chris@mimsy.umd.edu (Chris Torek) Newsgroups: comp.lang.c,comp.unix.programmer Subject: Re: erroneous "hello" from forked "hello world" process! Keywords: fork(), wait(), Hello World Message-ID: <26782@mimsy.umd.edu> Date: 1 Oct 90 07:15:03 GMT References: Followup-To: comp.unix.programmer Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 48 In article mef@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@cs.umd.edu Path: uunet!mimsy!chris