
deets at nospam
Nov 25, 2009, 2:15 PM
Post #2 of 4
(161 views)
Permalink
|
Sandy schrieb: > 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] > os._exit(0) > > From most of the tuts and examples I saw online, I expect it to print > a,b,c,d,e. > Sometimes (very rare) it prints something like this: > ab > c > d > e > 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. Yes, that's the case - you have a race-condition here. Two childs at the same time write, interleaving their data. To prevent this, you can use file-locking. http://docs.python.org/library/fcntl.html#fcntl.lockf Diez -- http://mail.python.org/mailman/listinfo/python-list
|