Results 1 to 2 of 2
Hi,
If I have two processes I created (let's say I forked), and both are doing something like:
Code:
while (1)
printf("my pid is %d\n",getpid());
The printouts never overlap. Instead ...
- 05-06-2009 #1Just Joined!
- Join Date
- Jan 2004
- Posts
- 6
Linux process synchronization
Hi,
If I have two processes I created (let's say I forked), and both are doing something like:
The printouts never overlap. Instead each line is nicely printed.Code:while (1) printf("my pid is %d\n",getpid());
This means that there is some kind of synchronization mechanism, protecting the stdout.
My question is how exactly is this done?
if I run ipcs -s, I will see no semaphores in the system, but if I write a code which pause() upon a signal, and attempt to synchronize processes with the signal, my printouts will eventually deadlock (and ipcs -s will show one semaphore...).
Thanks.
- 05-06-2009 #2Linux Guru
- Join Date
- Apr 2009
- Location
- I can be found either 40 miles west of Chicago, or in a galaxy far, far away.
- Posts
- 8,961
Stdout uses buffered i/o. When printf() finds a new-line character then it will flush the buffered output. I think that stderr is not buffered, so if you were to use fprintf(stderr,...) instead, I think you would get intermixed output. In any case, once the buffer for stdout is full, it will be flushed anyway, so if your output is large, it can still get intermixed.
Note that C++ output operators work the same way, and the endl i/o manipulator flushes the stream after inserting the new-line. IE:should work the same way as your C example.Code:while (1) cout << "my pid is " << dec << getpid() << endl;Sometimes, real fast is almost as good as real time.
Just remember, Semper Gumbi - always be flexible!


Reply With Quote
