将进程写入其stdin后的后台处理

2024-03-29 09:38:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是linux/cpython3.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等


Tags: fromimportenvbashbintimelinuxusr
2条回答

一种解决方法可能是“守护”您的cat:fork,然后再次快速fork并在第二个进程中退出,第一个进程等待第二个进程。第三个进程可以exec()cat,它将从其父进程继承其文件描述符。因此,您需要先创建一个管道,然后在子对象中关闭stdin并从管道中复制它。你知道吗

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

从另一个进程运行子进程,该进程的唯一任务是等待它。你知道吗

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)

相关问题 更多 >