Python Popen管道的第一个进程无法被终止

0 投票
1 回答
1653 浏览
提问于 2025-04-16 02:43

我在用这段代码

p1 = Popen(['rtmpdump'] + cmd_args.split(' '), stdout=PIPE)
p2 = Popen(player_cmd.split(' '), stdin=p1.stdout, stderr=PIPE)
p2.wait()
# try to kill rtmpdump
# FIXME: why is this not working ?
try:
    p2.stdin.close()
    p1.stdout.close()
    p1.kill()
except AttributeError:
    # if we use python 2.5
    from signal import SIGTERM, SIGKILL
    from os import kill
    kill(p1.pid, SIGKILL)

p1 结束时,p2 也会结束。

但是问题是:

如果我手动关闭 p2(它是 mplayer),那么 rtmpdump/p1 还是会继续运行。

我尝试了很多方法,比如上面提到的,但还是无法结束它。

我还试过加上 close_fds=True

所以可能是 rtmpdump 还在尝试写入标准输出(stdout)。但为什么这会导致 kill() 失败呢?

完整源代码:http://github.com/solsticedhiver/arte-7.py

1 个回答

0

这里有个解决办法。在调用 kill() 之后,记得再调用 wait(),这样才能真正结束那个“僵尸进程”。

# kill the zombie rtmpdump
try:
  p1.kill()
  p1.wait()
except AttributeError:
    # if we use python 2.5
    from signal import SIGKILL
    from os import kill, waitpid
    kill(p1.pid, SIGKILL)
    waitpid(p1.pid, 0)

撰写回答