confused with os.fork()
python at mrabarnett.plus.com
Wed Nov 25 23:33:50 CET 2009
> Hi all,
> I am a little bit confused about os.fork().
> Say I have the following code.
> import os
> a = ['a','b','c','d','e']
> for i in xrange(len(a)):
> pid = os.fork()
> if not pid:
> print a[i]
>>From most of the tuts and examples I saw online, I expect it to print
> Sometimes (very rare) it prints something like this:
> I thought there is no way a parent process can enter the 'if'.
> Can anyone explain this behaviour? Is it the case where parent is
> forking a child even before the previous child is printing? In that
> case is there a way to prevent that? I can use os.wait(), but I don't
> want to wait till the child is finished, just don't want to mix the
> child processes, that's it.
The parent isn't entering the 'if' statement. os.fork() simply forks the
process and then both the parent and the child processes continue.
All of the child processes run independently and there's no guarantee as
to the order in which they'll print, and there's nothing to stop the
printouts from being mixed together (you would need to protect the
'print' with a mutex to do that).
More information about the Python-list