python子进程关闭fd_在python子进程中读取fd#3

我认为您需要使用低级操作系统API在fd 3上设置管道,例如:import os, sys

# No other fds have been opened, so the lowest available are used (3, 4)

read, write = os.pipe()

# We want the child to write into fd#3, but right now that's the read

# end of the pipe, so do a little switching around:

temp = os.dup(read)

os.dup2(write, read)

os.dup2(temp, write)

os.close(temp)

read, write = write, read # swap actual values to avoid confusion

pid = os.fork()

if pid == 0: # child

os.close(read)

try:

os.execl('/bin/bash', 'bash', '-c', 'echo testing...>&3')

except OSError:

sys.exit(1)

else: # parent

os.close(write)

progress = os.fdopen(read)

print progress.read()

os.wait()

基本上,创建管道,并交换读/写端,以便写端位于fd#3上(将使用最低可用的fd,因此请确保尚未打开任何其他fd)。在

然后,叉开并关闭父级和子级中适当的管端。然后我们可以在子对象中执行目标,在我的例子中,我用bash作为例子。在父对象中,我们可以在管道的读取端构建一个普通的类似文件的对象,然后继续执行它,而不必担心底层API。在

如果在管道的读取端设置FD_CLOEXEC,那么可以使用subprocess模块,但是仍然需要执行低级调用来设置管道,因此这样做没有太大好处。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值