off topic: combined output of concurrent processes

Ed Greshko Ed.Greshko at greshko.com
Sat Apr 14 02:33:48 UTC 2012


On 04/14/2012 09:35 AM, Amadeus W.M. wrote:
> This is not Fedora specific, so apologies for posting it here. I used to 
> post this kind of questions in comp.linux.misc or the like but I don't 
> have access to usenet groups anymore.
>
> So here is the question. Suppose I have several processes that run 
> concurrently and each outputs stuff to stdout. Can the combined output be 
> intermingled? 
>
>
> Example: script ioTest.sh:
>
>
> #!/bin/bash
>
> i=0
> while [ $i -lt 100 ];
> do
>     echo "AAAAA" &    # e.g. 500 As
>     echo "BBBBB" & 
>     echo "CCCCC" & 
>
>     i=$(($i+1))
> done
>
>
> Then 
>
> ./ioTest.sh > out
>
> The A's and B's and C's always seem to be in contiguous blocks of 500 in 
> the output file, but is that guaranteed? 
>
> Thanks!
>

No....  Not only that, you are placing the echo commands in the background.  So, it
is certainly possible that the script will finish before the echos are completed. 
Not only that, there is no guarantee that all output from the echos will be written
to "out".  You can see this if you put a sleep after the last echo.

[egreshko at meimei test]$ grep ^A out | wc
     97      97     582
[egreshko at meimei test]$ grep ^B out | wc
     94      94     564
[egreshko at meimei test]$ grep ^C out | wc
     96      96     576

Your results will vary depending on the number of CPU's.  If you have a single CPU
system, you may very well get all 300.

-- 
Never be afraid to laugh at yourself, after all, you could be missing out on the joke
of the century. -- Dame Edna Everage


More information about the users mailing list