简体   繁体   中英

signal.signal receives sigint/sigterm when child process ends

I have the following simplified example:

#!/usr/bin/python

import logging, logging.handlers
from multiprocessing import Process, Queue
import time, sys, signal

def child_proc(sleepr):

    print 'Child: Started child, waiting'
    time.sleep(sleepr)
    print 'Child: Ended sleep, exiting' 

def cleanup(a, b):
    print 'Main: Got SIGTERM: ' + str(a) + ' : ' + str(b)

print 'Main: Starting process'
child_proc_th = Process(target=child_proc, args=(3,))
child_proc_th.start()

print 'Main: Pausing main thread'
signal.signal(signal.SIGTERM, cleanup)
signal.pause()

print 'Main: Running again after pause'

Why does the signal.pause resume once the child_proc has finished? I only want it to resume if a sigterm is received... Is child_proc sending its exit signal up the stack to the parent process? Or is there another way to do this...?

TIA

signal.pause() blocks until any signal is received. When a child exits it sends SIGCHLD to the parent. This causes signal.pause() to return.

As far as I can tell to achieve what you want you have to signal.pause() in a loop until the correct signal is received.

Something like this:

sigtermreceived = False

def sigterm(signum, frame):
  global sigtermreceived
  sigtermreceived = True

signal.signal(signal.SIGTERM, sigterm)

while not sigtermreceived:
  signal.pause()

Note that there is also Process.join() :

child_proc_th = Process(target=child_proc, args=(3,))
child_proc_th.start()
child_proc_th.join()

This will block until the child process exits. Which is basically the behaviour you have now but without messing with signals.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM