【问题标题】:How to kill python script and its children if another instance of it is already running如果另一个实例已经在运行,如何杀死 python 脚本及其子脚本
【发布时间】: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。

【问题讨论】:

标签: python linux process system-calls


【解决方案1】:

你可以使用这个命令来杀死所有分配给python脚本的资源:

kill -9 `ps -ef | grep your_python_script.py | grep -v grep | awk '{print $2}'`

【讨论】:

    【解决方案2】:

    在新的会话组下运行您的程序并将会话组 ID 写入文件。当你的程序启动时,kill -SIGNAL -prevsessiongroup。这将杀死所有进程及其子进程等,除非其中一个显式更改会话组。我已经包含了包含您可以使用的代码 sn-ps 的 url。

    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/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-08
      • 2019-10-30
      • 2019-03-21
      • 2016-03-23
      • 2017-03-31
      • 1970-01-01
      • 2019-06-22
      • 1970-01-01
      相关资源
      最近更新 更多