Patrick
Patrick

Reputation: 75

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?

Upvotes: 5

Views: 340

Answers (1)

pilcrow
pilcrow

Reputation: 58534

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.

Upvotes: 3

Related Questions