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 ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
- 05-06-2009 #1
- Join Date
- Jan 2004
Linux process synchronization
If I have two processes I created (let's say I forked), and both are doing something like:
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...).
- 05-06-2009 #2
- Join Date
- Apr 2009
- I can be found either 40 miles west of Chicago, or in a galaxy far, far away.
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: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!