Find the answer to your Linux question:
Results 1 to 2 of 2
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1

    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());
    The printouts never overlap. Instead each line is nicely printed.
    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...).


  2. #2
    Linux Guru Rubberman's Avatar
    Join Date
    Apr 2009
    I can be found either 40 miles west of Chicago, in 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:
    while (1)
        cout << "my pid is " << dec << getpid() << endl;
    should work the same way as your C example.
    Sometimes, real fast is almost as good as real time.
    Just remember, Semper Gumbi - always be flexible!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts