6

How can I run a command from a python script and delegate to it signals like Ctrl+C?

I mean when I run e.g:

from subprocess import call
call(["child_proc"])

I want child_proc to handle Ctrl+C

remdezx
  • 2,939
  • 28
  • 49
  • Can you be a bit more clear on what you want to accomplish? What do you want the child process to do? – TheSoundDefense Jul 24 '14 at 14:13
  • 1
    @remdezx Do you want signals sent to the parent process to be forwarded to child, or do you just want to be able to send signals to the child from the parent? – dano Jul 24 '14 at 14:21
  • I want signals sent to the parent to be forwarded to child. – remdezx Jul 24 '14 at 17:58

1 Answers1

2

I'm guessing that your problem is that you want the subprocess to receive Ctrl-C and not have the parent Python process terminate? If your child process initialises its own signal handler for Ctrl-C (SIGINT) then this might do the trick:

import signal, subprocess

old_action = signal.signal(signal.SIGINT, signal.SIG_IGN)
subprocess.call(['less', '/etc/passwd'])
signal.signal(signal.SIGINT, old_action)         # restore original signal handler

Now you can hit Ctrl-C (which generates SIGINT), Python will ignore it but less will still see it.

However this only works if the child sets its signal handlers up properly (otherwise these are inherited from the parent).

mhawke
  • 84,695
  • 9
  • 117
  • 138
  • 1
    you should probably set: preexec_fn=restore_signal, where restore_signal restores SIGINT to SIG_DFL. preexec_fn is run in the child (after fork(), before exec\*()). – jfs Jul 31 '14 at 20:24
  • "otherwise these [signal handlers] are inherited from the parent" -- is this a python thing or a unix thing? Also, any links for further reading on process signaling and inheritance? – bennlich Aug 02 '17 at 20:23
  • 1
    @bennlich: inheritance of signal disposition is certainly a Unix thing - I'm not sure about its implementation on Windows. Use the Linux man pages [`man 7 signal`](https://linux.die.net/man/7/signal) for reference, and _search_ for additional resources if you need. – mhawke Aug 03 '17 at 00:34