You can not. A process cannot read its own exit code. It doesn’t make much sense. But for the forced completion of the process, the OS must send a signal to this process. While this is not SIGKILL and / or SIGSTOP, you can intercept it through the signal library. SIGKILL and SIGSTOP cannot be blocked, for example. if someone does kill -9, then you cannot do anything.
To use the signal library:
import signal
import sys
def handler(signum, frame):
with open('log.log', 'a') as fo:
fo.write('Force quit on %s.\n' % signum)
sys.exit(1)
signal.signal(signal.SIGINT, handler)
signal.signal(signal.SIGHUP, handler)
signal.signal(signal.SIGTERM, handler)
When the terminal closes, it sends SIGHUP to the process.
SIGINT is used to interrupt CTRL-C.
SIGTERM is similar to SIGKILL. The difference is that the process can catch it. This is a "graceful murder."
IMPORTANT: This is true for all POSIX systems. I do not know much about other OSs.
source
share