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..."