🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.unix.internals
Article #2394

Re: printf() & fork() ......

#2394
From: Aaron Orenstein
Date: Sun, 22 Nov 1992 01:41
71 lines
2320 bytes
In article <1992Nov19.133035.172@ccsun7.csie.nctu.edu.tw>, mchuang@csie.nctu.edu.tw (Ming-Chuan Huang) writes:
-> Hello:
-> 
-> #include <stdio.h>
-> 
-> program 1:
-> 
-> void main()
-> {
->     printf("Hello ");
->     if (fork() == 0)
->         printf("world\n");
-> }
-> 
-> result:
-> Hello Hello world
-> 
-> program 2:
-> 
-> void main()
-> {
->     printf("Hello \n");
->     if (fork() == 0)
->         printf("world\n");
-> }
-> 
-> result:
-> Hello 
-> world
-> 
-> 
-> is there anybody who knows the difference between the two programs ?
-> 
->                                                       mchuang
->                                      mchuang@csie.nctu.edu.tw

Your problem is that you are using buffered I/O.
under unix, printf() does not actually output the information until
either a newline is printed, or the output is flushed.  (Output is automatically
flushed when you try to get input).  So what is happening is this:

You do a printf("Hello ") and it fills the buffer with "Hello ".  When you
fork, the child gets a copy of the buffer.  The parent exits, and flushes it's buffer which outputs "Hello " on the screen.  The child, adds "world" to it's
buffer and then, since you gave it a newline, it flushes the buffer.  So the
child prints out "Hello world"

In the second example, the newline at the end of the first printf() is flushing
the buffer so the buffer is empty when the child starts...

Your problem could be solved with the following code:
void main()
{
  printf("Hello ");
  fflush(stdout);
  if(fork()==0) printf("world\n");
}

result:
Hello world



	Anything else?

    Good luck
	- Aaron

-- 
--------------------
"The Code is free, It's the comments that cost a lot..."
Aaron Orenstein	(aorenste@cs.ulowell.edu, 129.63.1.11)
Technical Details
Message-ID: <By3Gp5.DsK@ulowell.ulowell.edu>
Path: arc1-ca.pugleaf.net!sparky!uunet!ulowell!img.ulowell.edu!aorenste
References: <1992Nov19.133035.172@ccsun7.csie.nctu.edu.tw>

Show Full Headers
Complete Article Headers
Newsgroups: comp.unix.internals
Path: arc1-ca.pugleaf.net!sparky!uunet!ulowell!img.ulowell.edu!aorenste
From: aorenste@cs.ulowell.edu (Aaron Orenstein)
Subject: Re: printf() & fork() ......
Message-ID: <By3Gp5.DsK@ulowell.ulowell.edu>
Sender: usenet@ulowell.ulowell.edu (News manager - ulowell)
Organization: Interactive Media Group - University of Massachusetts at Lowell
References:  <1992Nov19.133035.172@ccsun7.csie.nctu.edu.tw>
Date: Sun, 22 Nov 1992 01:41:29 GMT
Lines: 71