【发布时间】:2017-03-28 04:16:11
【问题描述】:
我需要编写一段代码来检查是否有另一个同名的 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。
【问题讨论】:
-
如果你能得到subp_test.py pid,你也可以查询进程的尾部,psutil.Process应该可以工作stackoverflow.com/questions/40509813/…和pstreeunix.stackexchange.com/questions/67668/…
标签: python linux process system-calls