subprocess - Python: How to prevent subprocesses from receiving CTRL-C / Control-C / SIGINT -
i working on wrapper dedicated server running in shell. wrapper spawns server process via subprocess , observes , reacts output.
the dedicated server must explicitly given command shut down gracefully. thus, ctrl-c must not reach server process.
if capture keyboardinterrupt exception or overwrite sigint-handler in python, server process still receives ctrl-c , stops immediately.
so question is: how prevent subprocesses receiving ctrl-c / control-c / sigint?
somebody in #python irc-channel (freenode) helped me pointing out preexec_fn parameter of subprocess.popen(...):
if preexec_fn set callable object, object called in child process before child executed. (unix only)
thus, following code solves problem (unix only):
import subprocess import signal def preexec_function(): # ignore sigint signal setting handler standard # signal handler sig_ign. signal.signal(signal.sigint, signal.sig_ign) my_process = subprocess.popen( ["my_executable"], preexec_fn = preexec_function )
note: signal not prevented reaching subprocess. instead, preexec_fn above overwrites signal's default handler signal ignored. thus, solution may not work if subprocess overwrites sigint handler again.
another note: solution works sorts of subprocesses, i.e. not restricted subprocesses written in python, too. example dedicated server writing wrapper in fact written in java.
Comments
Post a Comment