python杀死父进程,但杀死子进程

2024-04-27 12:02:23 发布

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

当我试图终止一个python进程时,通过os.system启动的子进程不会同时终止。

Killing child process when parent crashes in pythonPython Process won't call atexit (atexit看起来不适用于信号)

这是否意味着我需要自己处理这种情况?如果是,最好的方法是什么?

> python main.py
> ps
4792 ttys002    0:00.03 python run.py
4793 ttys002    0:00.03 python loop.py 
> kill -15 4792
> ps 
4793 ttys002    0:00.03 python loop.py

示例代码:

主.py

import os
os.system('python loop.py')

循环.py

import time

while True:
    time.sleep(1000)

更新1

我做了一些实验,找到了一个可行的版本,但仍然混淆了逻辑。

import os
import sys
import signal
import subprocess


def sigterm_handler(_signo, _stack_frame):
    # it raises SystemExit(0):
    print 'go die'
    sys.exit(0)


signal.signal(signal.SIGTERM, sigterm_handler)

try:
    # os.system('python loop.py') 
    # use os.system won't work, it will even ignore the SIGTERM entirely for some reason 
    subprocess.call(['python', 'loop.py'])
except:
    os.killpg(0, signal.SIGKILL)

Tags: pyimportloopsignaltime进程ossys
1条回答
网友
1楼 · 发布于 2024-04-27 12:02:23

在您的示例中,kill -15 4792SIGTERM发送到run.py——它不向loop.py(或其父shell)发送任何内容。SIGTERM默认情况下不会传播到进程树中的其他进程。

os.system('python loop.py')至少开始两个进程shell和python进程。您不需要它;使用subprocess.check_call(),运行一个没有隐式shell的子进程。顺便说一下,如果你的subprocess is a Python script; consider importing it and running corresponding functions instead

os.killpg(0, SIGKILL)向当前进程组发送SIGKILL信号。shell为每个管道创建一个新的进程组(作业),因此父进程中的os.killpg()对子进程没有影响(请参阅更新)。见How to terminate a python subprocess launched with shell=True

#!/usr/bin/env python
import subprocess
import sys

try:
    p = subprocess.Popen([executable, 'loop'])
except EnvironmentError as e: # 
    sys.exit('failed to start %r, reason: %s' % (executable, e))
else:
    try: # wait for the child process to finish
        p.wait()
    except KeyboardInterrupt: # on Ctrl+C (SIGINT)
        #NOTE: the shell sends SIGINT (on CtrL+C) to the executable itself if
        #  the child process is in the same foreground process group as its parent 
        sys.exit("interrupted")

更新

似乎os.system(cmd)没有为cmd创建新的进程组:

>>> import os
>>> os.getpgrp()
16180
>>> import sys
>>> cmd = sys.executable + ' -c "import os; print(os.getpgrp())"'
>>> os.system(cmd) #!!! same process group
16180
0
>>> import subprocess
>>> import shlex
>>> subprocess.check_call(shlex.split(cmd))
16180
0
>>> subprocess.check_call(cmd, shell=True)
16180
0
>>> subprocess.check_call(cmd, shell=True, preexec_fn=os.setpgrp) #!!! new
18644
0

因此,示例中的os.system(cmd)应该被os.killpg()调用终止。

不过,如果我在bash中运行它,它确实会为每个管道创建一个新的进程组:

$ python -c "import os; print(os.getpgrp())"
25225
$ python -c "import os; print(os.getpgrp())"
25248

相关问题 更多 >