我需要編寫一段代碼來檢查是否有另一個同名的python腳本實例正在運行,殺死它及其所有子代並做好腳本的工作。在我去解決方案,我有這樣的代碼:如何殺死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」在其命令,但沒有「subp_test.py不會殺some_other_script.py或其他程序的所有進程' 在裏面。
腳本subp_test.py將執行的調用是意想不到的,但據我所知,他們應該在流程樹下。
那麼如何訪問subp_test.py的所有子節點以便在subp_test.py的新實例開始運行時將其殺死?
另外,有沒有更好的方法來實現這個邏輯?
我在Ubuntu 10.04上使用Python 2.6.5。
如果你能得到的subp_test.py PID,您還可以查詢進程的尾巴,psutil.Process應該工作http://stackoverflow.com/questions/40509813/get-pid遞歸子進程?noredirect = 1#comment68261789_40509813以及pstree http://unix.stackexchange.com/questions/67668/elegantly-get-list-of-descendant-processes –