当我浏览帖子时,我在here上遇到了下面的例子,它说需要调用proc1.stdout.close()
来适当退出{
import subprocess
proc1 = subprocess.Popen(['ps', 'cax'], stdout=subprocess.PIPE)
proc2 = subprocess.Popen(['grep', 'python'], stdin=proc1.stdout,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
proc1.stdout.close() # Allow proc1 to receive a SIGPIPE if proc2 exits.
out, err = proc2.communicate()
print('out: {0}'.format(out))
print('err: {0}'.format(err))
然而,我对此并不清楚。请纠正我的理解。在
SIGPIPE
在PIPE
试图写入已关闭的PIPE
时发生。在PIPE
是proc1
的stdout
,读卡器{stdin
。在proc2
退出并且proc1
试图将数据写入proc2
的{proc2
的stdin PIPE
在proc2
退出时关闭SIGPIPE
发生在proc1
处,因为proc1
试图写入关闭的proc2
的{根据我的理解,SIGPIPE
会发生,proc1
将退出,而不管{
我错过了什么?在
在阅读了@unutbu评论中的post之后。。。。。。在
我认为复制的文件描述符(proc1.stdout
)是writer管道,而不是reader管道。因此,有两个写入管道和一个读取管道彼此连接。在
因此,proc2
退出时将生成SIGPIPE
,因为proc2
只是一个有读卡器管道的进程(当proc2
退出时将关闭)。在
但是,上面的post似乎说明通过复制proc1.stdout
有两个读卡器管道,因此即使在proc2
退出后也不会生成{
So by closing p1.stdout immediately, you ensure that the only remaining filehandle reading from dmesg stdout is the grep process, and if that process were to exit, dmesg receives a SIGPIPE.
我不是说post是错的,但我只是想修正我的理解。提前谢谢你。在
在父进程和
^{pr2}$proc1
之间创建一个管道:p1.stdout
是父进程将从proc1
获取(stdout)输出的内容。在将管道副本从proc1连接到proc2:
通过调用
p1.stdout.close()
,我们关闭了管道的父进程一侧:现在当
proc2
终止时,它的管道一侧也将关闭:下次
proc1
试图写入管道时,会生成一个SIGPIPE信号, 它允许proc1
终止,因为它知道没有人监听其管道的另一端。在相关问题 更多 >
编程相关推荐