在写入stdin之后对进程进行后台处理

时间:2014-09-03 17:11:30

标签: python linux bash init zombie-process

我正在使用linux / cpython 3.3 / bash。这是我的问题:

#!/usr/bin/env python3
from subprocess import Popen, PIPE, DEVNULL
import time

s = Popen('cat', stdin=PIPE, stdout=DEVNULL, stderr=DEVNULL)
s.stdin.write(b'helloworld')
s.stdin.close()
time.sleep(1000)     #doing stuff

这会让cat成为一个僵尸(而且我很忙"做东西"并且可以“wait关于子进程”。在bash中是否有一种方法可以包装cat(例如通过创建一个孙子)来允许我写入cat的stdin,但是让init接管为家长吗? python解决方案也可以工作,我也可以使用nohup,disown等。

2 个答案:

答案 0 :(得分:1)

从另一个进程运行子进程,其唯一任务是等待它。

pid = os.fork()
if pid == 0:
     s = Popen('cat', stdin=PIPE, stdout=DEVNULL, stderr=DEVNULL)
     s.stdin.write(b'helloworld')
     s.stdin.close()
     s.wait()
     sys.exit()
time.sleep(1000)

答案 1 :(得分:0)

一种解决方法可能是" daemonize"你的cat:fork,然后快速再次fork并在第二个进程中退出,第一个wait()为第二个进程。然后第三个进程可以执行exec()cat,它将从其父级继承其文件描述符。因此,您需要先创建一个管道,然后关闭子项中的stdin,并从管道中复制它(

我不知道如何在python中做这些事情,但我相当肯定它应该是可能的。

相关问题