Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How do you catch UNIX signals received in subprocess?

I want my Python program to run a non-Python program, be notified of the Unix signals that the subprocess receives, and handle them. In this specific case I want to handle SIGXFSZ for my child process.

Is this possible?

like image 660
Patrick Avatar asked Oct 18 '22 06:10

Patrick


1 Answers

Generally, parent or other processes cannot catch/intercept/receive signals generated for another process.

However, if the SIGXFSZ terminates your child process, the parent can know this. If using python's subprocess module, a "negative [returncode] value -N indicates that the child was terminated by signal N (POSIX only)."

For example, on my system SIGXFSZ is signal no. 25, and thus death by XFSZ is a return code of -25:

$ python -c 'import signal; print(repr(signal.SIGXFSZ))'
<Signals.SIGXFSZ: 25>

$ python -c 'import subprocess; print(subprocess.call(["kill -XFSZ $$"], shell=True))'
-25

If not using the subprocess module, the fatal signal information is still encoded in the status returned to os.waitpid() via the helper functions WIFSIGNALED and WTERMSIG.

like image 56
pilcrow Avatar answered Oct 21 '22 07:10

pilcrow