How to stop SIGINT being passed to subprocess in python?

后端 未结 3 604
野性不改
野性不改 2021-02-04 06:33

My python script intercepts the SIGINT signal with the signal process module to prevent premature exit, but this signal is passed to a subprocess that I open wi

3条回答
  •  無奈伤痛
    2021-02-04 07:13

    Signal handlers are inherited when you start a subprocess, so if you use the signal module to ignore SIGINT (signal.signal(signal.SIGINT, signal.SIG_IGN)), then your child process automatically will also.

    There are two important caveats, though:

    • You have to set the ignore handler before you spawn the child process
    • Custom signal handlers are reset to the default handlers, since the child process won't have access to the handler code to run it.

    So if you need to customise your handling of SIGINT rather than just ignoring it, you probably want to temporarily ignore SIGINT while you spawn your child process, then (re)set your custom signal handler.

    If you're trying to catch SIGINT and set a flag so you can exit at a safe point rather than immediately, remember that when you get to that safe point your code will have to manually clean up its descendants, since your child process and any processes it starts will be ignoring the SIGINT.

提交回复
热议问题