Question
So I have this code (partially taken from python docs):
- import signal
- def handler(signum, frame):
- print 'Signal handler called with signal', signum
- s = signal.signal(signal.SIGINT, handler) # previous signal handler will be returned
- some_fancy_code() # this code is using subprocess.Popen() to call another script
- singal.signal(signal.SIGINT, s)
But when we replace 'handler' with 'signal.SIG_IGN', this propagation never happens. Modified snippet:
- import signal
- s = signal.signal(signal.SIGINT, signal.SIG_IGN)
- some_fancy_code() # this code is using subprocess.Popen() to call another script
- singal.signal(signal.SIGINT, s)
How-To
This is the specified POSIX behaviour of signals:
When you execute (fork/execve) your another script in the first case, the SIGINT handler is reset to the default handler in the another script (default behaviour is to terminate the process) - of course, the another script could install its own handler and change this behaviour.
However, in the second case, you've configured SIGINT to be ignored. This behaviour will be propagated to the another script, as indicated in the definition above. Again, the another script could change this behaviour by installing its own handler.
So this has nothing to do with Python directly. It is the expected behaviour of the underlying operating system's POSIX signal handling implementation.
PS. If you're wondering what fork() and execve() are, fork() creates a copy of the running process (a child) and execve() replaces the current process with another. This is the underlying mechanism used by subprocess.Popen() to run the 'another script': first make a copy of the current process and then replace it with the target process.
沒有留言:
張貼留言