Reputation: 6242
What does Python do under the covers by default if it receives a SIGTERM but there is no signal handler registered for it?
Upvotes: 51
Views: 18963
Reputation: 3413
Building on the answer of Thomas Wouters, python does not register a handler for the SIGTERM signal. We can see this by doing:
In[23]: signal.SIG_DFL == signal.signal(signal.SIGTERM,signal.SIG_DFL)
Out[23]: True
That means that the system will take the default action. On linux, the default action (according to the signal man page) for a SIGTERM is to terminate the process.
Terminating a process means that:
the process will simply not be allocated any more time slices during which it can execute code.
__exit__
method of context managers. It will not do those things because that particular python interpreter will never get the chance to execute another instruction. The process's memory and other resources (open files, network sockets, etc...) will be released back to the rest of the system.
Upvotes: 40
Reputation: 2814
Look at this example:
import time
class A:
def __init__(self):
print("A.__init__()")
def __del__(self):
print("A.__del__()")
a = A()
b = A()
time.sleep(10)
Under normal circumstances, the output would be:
A.__init__()
A.__init__()
A.__del__()
A.__del__()
But if you kill it with SIGTERM you get:
A.__init__()
A.__init__()
Terminated
Thus the program does not terminate cleanly (the destructors are not called).
Upvotes: 3
Reputation: 133405
Nothing. Python itself does not register a signal handler for it. You can check this in the interactive interpreter:
>>> import signal
>>> signal.signal(signal.SIGTERM, signal.SIG_DFL)
0
>>> signal.SIG_DFL
0
That shows signal.signal()
returning signal.SIG_DFL for signal.SIGTERM
. Contrast it with signal.SIGINT
, which does have a default signal handler (which raises KeyboardInterrupt
):
>>> signal.signal(signal.SIGINT, signal.SIG_DFL)
<built-in function default_int_handler>
Upvotes: 26