Python的多处理.Queue + Process:正确终止两个程序

时间:2011-10-19 19:52:50

标签: python process queue multiprocessing

鉴于此Python程序:

# commented out code are alternatives I tried that don't work.

from multiprocessing import Process, Queue
#from multiprocessing import Process, JoinableQueue as Queue

def start_process(queue):
    # queue.cancel_join_thread()
    while True:
        print queue.get()

if __name__ == '__main__':
    queue = Queue()
    # queue.cancel_join_thread()

    process = Process(target=start_process, args=(queue,))
    process.start()

    queue.put(12)
    process.join()

当我使用CTRL-C杀死此程序时,会发生这种情况:

$> python queuetest.py
12
^CTraceback (most recent call last):
  File "queuetest.py", line 19, in <module>
    process.join()
  File ".../python2.7/multiprocessing/process.py", line 119, in join
    res = self._popen.wait(timeout)
Process Process-1:
  File ".../python2.7/multiprocessing/forking.py", line 122, in wait
Traceback (most recent call last):
    return self.poll(0)
  File ".../python2.7/multiprocessing/forking.py", line 107, in poll
    pid, sts = os.waitpid(self.pid, flag)
  File ".../python2.7/multiprocessing/process.py", line 232, in _bootstrap
KeyboardInterrupt
    self.run()
  File ".../python2.7/multiprocessing/process.py", line 88, in run
    self._target(*self._args, **self._kwargs)
  File "queuetest.py", line 9, in start_process
    print queue.get()
  File ".../python2.7/multiprocessing/queues.py", line 91, in get
    res = self._recv()
KeyboardInterrupt

..如何在信号上正确终止两个处理?

我想要实现的目标:在我的非最小程序中,第二个进程拥有一个SocketServer,需要一个额外的交互式命令行界面。

1 个答案:

答案 0 :(得分:3)

解决方案是通过队列发送特定消息(例如,我的样本中的'exit'字符串),以终止worker(子进程)正常。当CTRL-C信号发送给所有孩子时,我们需要忽略它。 以下是示例代码:

from multiprocessing import Process, Queue

def start_process(queue):
  while True:
    try:
        m = queue.get()
        if m == 'exit':
            print 'cleaning up worker...'
            # add here your cleaning up code
            break
        else:
            print m
    except KeyboardInterrupt:
        print 'ignore CTRL-C from worker'


if __name__ == '__main__':
  queue = Queue()

  process = Process(target=start_process, args=(queue,))
  process.start()

  queue.put(12)

  try:
    process.join()
  except KeyboardInterrupt:
    print 'wait for worker to cleanup...'
    queue.put('exit')
    process.join()

    ## or to kill anyway the worker if is not terminated after 5 seconds ...
    ## process.join(5)
    ## if process.is_alive():
    ##     process.terminate()