it printed something twice
when i changed it into printf("something\n");
it printed once , why this and what fork is doing by seeing a \n
please help me!
Nothing to do with fork particularly; it's just helping you see the
effects of buffered i/o.
--
Please note new phone number: (781) 784-7547
Tony Lawrence
Unix/Linux Support Tips, How-To's, Tests and more: http://aplawrence.com
Free Unix/Linux Consultants list: http://aplawrence.com/consultants.html
It's a byproduct of how stdio buffering works
Your printf() statement is buffered into a block of memory, and will only be
written to the character special output device when the program either issues a
printf("\n") or a fflush(stdout). (If your stdout is directed to something other
than a character special output device, the buffer gets flushed with each
printf() statement.)
So, when you start a program with stdout directed to your terminal, you can only
expect to see printf() output when the printf() prints a newline, or the program
issues an explicit fflush(). At all other times, this program will buffer the
data in memory, waiting for one of those two conditions to occur.
Now, your program performs it's
printf("something");
and nothing comes out
Next, your program performs it's
fork();
and still nothing comes out. However, you now have two programs running, each
with the "something" stashed in a stdout buffer (remember, in essence, fork()
copies the current state of the forking program, so that both the original and
the new processes have the same values in all their variables, including
buffers).
When the first program terminates, the stdio library flushes that program's
stdout buffer prior to the exit, so you see the first "something", coming from
the buffer in the first program.
Now, the second program terminates, and the stdio library flushes _that_
program's stdout buffer prior to the exit. You now see the second "something",
coming from the buffer in the second program.
And, all this changes when you run your program with stdout redirected to a
file, because, since stdout is pointing to a file, the stdio library ensures
that the printf() before the fork() is flushed immediately, rather than being
deferred.
Lew Pitcher
IT Consultant, Development Services
Toronto Dominion Bank Financial Group
(Opinions expressed are my own, not my employers')