我需要编写一段代码来检查是否有另一个具有相同名称的python脚本实例正在运行,杀死它及其所有子代,并完成脚本的工作。在我的解决方案上,我有这个代码:
import os, sys
import time
import subprocess
from subprocess import PIPE,Popen
import os
import signal
if sys.argv[1] == 'boss':
print 'I am boss', \
"pid:", os.getpid(), \
"pgid:", os.getgid()
# kill previous process with same name
my_pid=os.getpid()
pgrep = Popen(['pgrep', '-f', 'subp_test.py'], stdout=PIPE)
prev_pids=pgrep.communicate()[0].split()
print 'previous processes:' , prev_pids
for pid in prev_pids:
if int(pid) !=int(my_pid):
print 'killing', pid
os.kill(int(pid), signal.SIGKILL)
# do the job
subprocess.call('python subp_test.py 1', shell=True)
subprocess.call('python subp_test.py 2', shell=True)
subprocess.call('python some_other_script.py', shell=True)
else:
p_num = sys.argv[1]
for i in range(20):
time.sleep(1)
print 'child', p_num, \
"pid:", os.getpid(), \
"pgid:", os.getgid(), \
":", i
这将终止在其命令中具有子字符串'subp_test.py'的所有进程,但不会杀死some_other_script.py或其中没有'subp_test.py'的程序。
脚本subp_test.py将执行的调用是意外的,但据我所知,它们应该位于进程树中。
那么当一个新的subp_test.py实例开始运行时,如何访问subp_test.py的所有子节点以杀死它们?
此外,有更好的方法来实现这个逻辑吗?
我在Ubuntu 10.04上使用Python 2.6.5。
答案 0 :(得分:0)
在新会话组下运行程序,并将会话组ID写入文件。程序启动时,请杀死-SIGNAL -prevsessiongroup。这会杀死所有进程及其子进程等,除非其中一个进程明确更改了会话组。我已经包含了包含您可以使用的代码片段的网址。
https://docs.python.org/2/library/os.html#os.setsid http://web.archive.org/web/20131017130434/http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/
答案 1 :(得分:0)
你可以使用这个命令杀死分配给python脚本的所有资源:
kill -9 `ps -ef | grep your_python_script.py | grep -v grep | awk '{print $2}'`