像这样:
if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
...
Run Code Online (Sandbox Code Playgroud)
虽然我读过man fcntl,但我无法弄清楚它的作用.
我有点难以理解解决这个简单问题的python方法是什么.
我的问题很简单.如果您使用以下代码,它将挂起.这在子流程模块doc中有详细记载.
import subprocess
proc = subprocess.Popen(['cat','-'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
)
for i in range(100000):
proc.stdin.write('%d\n' % i)
output = proc.communicate()[0]
print output
Run Code Online (Sandbox Code Playgroud)
寻找一个解决方案(有一个非常有洞察力的线程,但我现在已经丢失了)我发现这个解决方案(以及其他)使用了一个显式的fork:
import os
import sys
from subprocess import Popen, PIPE
def produce(to_sed):
for i in range(100000):
to_sed.write("%d\n" % i)
to_sed.flush()
#this would happen implicitly, anyway, but is here for the example
to_sed.close()
def consume(from_sed):
while 1:
res = from_sed.readline()
if not res:
sys.exit(0)
#sys.exit(proc.poll())
print 'received: ', [res]
def main():
proc = Popen(['cat','-'],stdin=PIPE,stdout=PIPE)
to_sed = proc.stdin
from_sed = …Run Code Online (Sandbox Code Playgroud)