Linux中的Python:使用shell杀死进程和子进程
Q:给定一个一直在运行的python程序,该程序作为其子程序运行另一个python程序,如何使用python shell杀死进程[即,获取进程PID,然后执行Linux中的Python:使用shell杀死进程和子进程,python,linux,shell,Python,Linux,Shell,Q:给定一个一直在运行的python程序,该程序作为其子程序运行另一个python程序,如何使用python shell杀死进程[即,获取进程PID,然后执行kill-9] 更多详细信息: 我有一个脚本如下: from subprocess import * while True: try: Popen("python ...").wait() # some scrpipt except: exit(1) try: Pop
kill-9
]
更多详细信息:
我有一个脚本如下:
from subprocess import *
while True:
try:
Popen("python ...").wait() # some scrpipt
except:
exit(1)
try:
Popen("python ...").wait() # some scrpipt
except:
exit(1)
现在,当我想杀死这个进程及其子进程时,我:
“ps-ef | grep python”
获取PIDkill-9
终止进程杀死-9
的时候没有。使用SIGINT(-2
)或SIGTERM(-15
)杀死,并通过注册处理优雅退出的清理功能,使用信号模块捕获该信号
import sys
import signal
def cleanup_function(signal, frame):
# clean up all resources
sys.exit(0)
signal.signal(signal.SIGINT, cleanup_function)
在此代码中,父级将等待子级的退出状态。若父级正在获取其存在状态,则只有它将继续进行下一次迭代 此外,您无法捕获
SIGKILL
(SIGKILL
和SIGSTOP
是无法捕获的信号)
-9
表示SIGKILL
您可以在任何其他信号的情况下实现信号
处理程序
import os
import time
def my_job():
print 'I am {0}, son/daughter of {1}'.format(os.getpid(), os.getppid())
time.sleep(50)
pass
if __name__ == '__main__':
while True:
pid = os.fork()
if pid > 0:
expired_child = os.wait() # if child is getting killed, will return a tuple containing its pid and exit status indication
if expired_child:
continue
else:
my_job()
你想从哪里杀它?