重定向子进程的stdout

时间:2018-04-11 20:09:02

标签: python unix pipe stdout

我正在尝试创建一个程序,它会分叉子进程,然后监视它的标准输出。我的理解是,这应该可以通过创建一组管道fds,然后使用dup将管道的写入端设置为子节点中的STDOUT来实现。下面的代码试图这样做

import os
import sys
import time
pid = os.fork()
pr, pw = os.pipe()

if pid == 0: #Inside child
    os.close(pr)
    os.dup2(pw, sys.stdout.fileno())
    print("Inside the child")
    exit(1)

print("Inside parent, waiting for child output..")
result = os.read(pr, 1024)
print(result)

但是会产生破裂的管道。错误如下。

BrokenPipeError: [Errno 32] Broken pipe
Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>
BrokenPipeError: [Errno 32] Broken pipe
Traceback (most recent call last):
File "/tmp/master.py", line 14, in <module>
  result = os.read(pr, 1024)

我看了几个例子,但似乎无法弄清楚我做错了什么。该错误表明管道的读取结束过早关闭,但情况似乎并非如此。

0 个答案:

没有答案
相关问题