【问题标题】:Why kill command can not terminate nohup python thread为什么kill命令不能终止nohup python线程
【发布时间】:2017-03-23 06:45:57
【问题描述】:

代码:

res = Subprocess.Popen(cmd,executable="/bin/bash", shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)

while not res.poll():
     do something....

我运行 python 代码如下: nohup python my_script.py &

然后我想终止脚本:

kill pid_of_the_script

但它不起作用(所以由 Subprocess.Popen 创建的 cmd 过程仍然存在)我必须使用:

kill -9 pid_of_the_script

为什么 kill 命令在这里不起作用?

由于 kill -9 也不会杀死 cmd 进程, 当我捕获 SIGTERM 信号时(这是问题,当我发送 kill 命令时,脚本无法捕获此信号,我确实将 SIGTERM 信号注册到信号处理程序),处理程序首先杀死 cmd 进程然后使用kill -9 杀死脚本本身(基于 pid)。

更新: 也许 thread.join() 方法会导致这种情况。 在主线程调用join的地方,主线程好像不能处理信号...

【问题讨论】:

标签: python multithreading signal-processing


【解决方案1】:

如果您无法退出打开命令窗口的进程,您可以尝试使用os.exit(1),它将为您完成这项工作。

【讨论】:

    【解决方案2】:

    我使用以下代码作为解决方法:

    thread1.start()         # process in thread1 is an infinite task
    while some_condition:   # use a infinite loop here
         time.sleep(10)
    thread1.join()          # join after the loop, so before calling join, the
                            # main thread can response to the signals            
    

    添加信号处理程序:

    def signal_handler(signum, frame):
        print "receive sig %d " % signum
        # kill the process started by thread1
        ...
        # modify condition value here, so the above infinite loop can exit now
        ...
    

    将信号处理程序注册到 SIGTERM

    signal.signal(signal.SIGTERM, signal_handler)
    

    现在我可以使用 ctrl+C 或 kill 来终止主进程及其子进程。

    由于thread1中的任务是无限的,看来设置为守护线程也可以,所以主线程不需要调用join(),sleep就可以了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-01
      • 2016-05-02
      • 2020-04-18
      • 2014-01-03
      • 1970-01-01
      • 2021-03-11
      • 2022-01-14
      • 2014-11-18
      相关资源
      最近更新 更多