【发布时间】:2015-08-03 16:15:16
【问题描述】:
这是previous question的后续行动:
我有一个parent.py:
from sys import argv
from random import randrange
from subprocess import Popen, PIPE
lines = int(argv[1])
procs = int(argv[2])
cmd = ["python", "child.py"]
children = list()
for p in range(procs):
children.append([0,Popen(cmd, stdin=PIPE, stdout=PIPE)])
for i in range(lines):
child = children[randrange(procs)]
child[0] += 1
child[1].stdin.write("hello\n")
for n,p in children:
p.stdin.close()
out = p.stdout.read()
p.stdout.close()
exitcode = p.wait()
print n,out,exitcode
assert n == int(out)
assert lines == sum(n for n,_ in children)
还有一个child.py:
import sys
l = list()
for line in sys.stdin:
l.append(line)
sys.stdout.write(str(len(l)))
当我创建一个孩子时,它工作正常:
$ python parent.py 100 1
100 100 0
但是,多子死锁:
$ python parent.py 100 2 &
[1] 59492
$ strace -p 59492
Process 59492 attached - interrupt to quit
read(5, ^C <unfinished ...>
Process 59492 detached
$ pstree -p 59492
python(59492)-+-python(59494)
`-python(59495)
$ strace -p 59494
Process 59494 attached - interrupt to quit
read(0, ^C <unfinished ...>
Process 59494 detached
$ strace -p 59495
Process 59495 attached - interrupt to quit
read(0, ^C <unfinished ...>
Process 59495 detached
为什么即使我关闭了他们的stdin,孩子们仍然继续read()?
PS。关闭所有子标准输入从其中任何一个读取之前关闭的简单更改解决问题:
$ python parent.py 10000 4
2486 2486 0
2493 2493 0
2531 2531 0
2490 2490 0
为什么?!
【问题讨论】:
-
python parent.py 100 2每次都为我工作。 -
@Celada:你用的是python 2.7,对吧?
-
是的,我使用的是 2.7.3。
-
您的意思是“注意...的简单更改”?
-
@G-Man:是的!已修复,谢谢!