捕获Ctrl + C/SIGINT并在python中正常退出多进程 [英] Catch Ctrl+C / SIGINT and exit multiprocesses gracefully in python

查看:221
本文介绍了捕获Ctrl + C/SIGINT并在python中正常退出多进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在多进程python程序中捕获 Ctrl + C 并正常退出所有进程,我需要在Unix和Windows上均可使用的解决方案.我尝试了以下方法:

How do I catch a Ctrl+C in multiprocess python program and exit all processes gracefully, I need the solution to work both on unix and windows. I've tried the following:

import multiprocessing
import time
import signal
import sys

jobs = []

def worker():
    signal.signal(signal.SIGINT, signal_handler)
    while(True):
        time.sleep(1.1234)
        print "Working..."

def signal_handler(signal, frame):
    print 'You pressed Ctrl+C!'
    # for p in jobs:
    #     p.terminate()
    sys.exit(0)

if __name__ == "__main__":
    for i in range(50):
        p = multiprocessing.Process(target=worker)
        jobs.append(p)
        p.start()

这是可行的,但我认为这不是正确的解决方案.

And it's kind of working, but I don't think it's the right solution.

推荐答案

先前接受的解决方案具有竞争条件,但没有竞争条件使用mapasync函数.

The previously accepted solution has race conditions and it does not work with map and async functions.

使用multiprocessing.Pool处理 Ctrl + C /SIGINT的正确方法是:

The correct way to handle Ctrl+C/SIGINT with multiprocessing.Pool is to:

  1. 在创建进程Pool之前,使进程忽略SIGINT.这样创建的子进程继承了SIGINT处理程序.
  2. 在创建Pool之后,在父进程中恢复原始的SIGINT处理程序.
  3. 使用map_asyncapply_async而不是阻止mapapply.
  4. 等待结果超时,因为默认阻塞将等待忽略所有信号.这是Python错误 https://bugs.python.org/issue8296 .
  1. Make the process ignore SIGINT before a process Pool is created. This way created child processes inherit SIGINT handler.
  2. Restore the original SIGINT handler in the parent process after a Pool has been created.
  3. Use map_async and apply_async instead of blocking map and apply.
  4. Wait on the results with timeout because the default blocking waits to ignore all signals. This is Python bug https://bugs.python.org/issue8296.


放在一起:


Putting it together:

#!/bin/env python
from __future__ import print_function

import multiprocessing
import os
import signal
import time

def run_worker(delay):
    print("In a worker process", os.getpid())
    time.sleep(delay)

def main():
    print("Initializng 2 workers")
    original_sigint_handler = signal.signal(signal.SIGINT, signal.SIG_IGN)
    pool = multiprocessing.Pool(2)
    signal.signal(signal.SIGINT, original_sigint_handler)
    try:
        print("Starting 2 jobs of 5 seconds each")
        res = pool.map_async(run_worker, [5, 5])
        print("Waiting for results")
        res.get(60) # Without the timeout this blocking call ignores all signals.
    except KeyboardInterrupt:
        print("Caught KeyboardInterrupt, terminating workers")
        pool.terminate()
    else:
        print("Normal termination")
        pool.close()
    pool.join()

if __name__ == "__main__":
    main()

正如@YakovShklarov指出的那样,在父进程中忽略信号和忽略信号之间存在时间窗口,在此期间信号可能会丢失.使用pthread_sigmask来临时阻止父进程中的信号传递可以防止信号丢失,但是在Python-2中不可用.

As @YakovShklarov noted, there is a window of time between ignoring the signal and unignoring it in the parent process, during which the signal can be lost. Using pthread_sigmask instead to temporarily block the delivery of the signal in the parent process would prevent the signal from being lost, however, it is not available in Python-2.

这篇关于捕获Ctrl + C/SIGINT并在python中正常退出多进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆