Him
Him

Reputation: 5551

What happens when a `subprocess.call` receives a kill signal?

Does the signal continue down to the called process?

e.g., I issue a SIGINT to a python process that is waiting on a subprocess.call to finish. subprocess.call is interrupted. What happens to the child process? What about SIGTERM, etc?

@zerkms points out that killing a parent process doesn't, in general, pass kill signals down to child processes. However, it is easy to check that some such thing happens with the python subprocess.call function:

Terminal 1

$ python3
>>> import subprocess
>>> with open("foo.py", "w") as f:
...     f.write("import time; time.sleep(6000)")
... 
29
>>> subprocess.call(["python3", "foo.py"])

Terminal 2

$ ps aux | grep foo.py
scott 3716  ........  20:03   0:00 python3 foo.py
scott 3720  ........  20:03   0:00 grep --color=auto foo.py

Terminal 1

<Ctrl-C>
^CTraceback (most recent call last):
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/subprocess.py", line 289, in call
    return p.wait(timeout=timeout)
  File "/usr/lib/python3.6/subprocess.py", line 1477, in wait
    (pid, sts) = self._try_wait(0)
  File "/usr/lib/python3.6/subprocess.py", line 1424, in _try_wait
    (pid, sts) = os.waitpid(self.pid, wait_flags)
KeyboardInterrupt

Terminal 2

$ ps aux | grep foo.py

scott 3722  ........  20:04   0:00 grep --color=auto foo.py

So it seems that, at the very least, the argument of subprocess.call is getting killed in this scenario.

Upvotes: 4

Views: 91

Answers (1)

user58697
user58697

Reputation: 7923

The linked question addresses the different scenario. There a signal is sent to the process (by specifying the pid). And indeed the child precesses survive.

In your situation, <Ctrl-C> is not a signal per se; it instructs the terminal driver to send SIGINT to every process in the associated process group.

Depending on how the child process was created, it may remain in the parent process group, or it may dissociate itself from it. In the latter case, <Crtl-C> typed in the parent's controlling terminal would have no effect on the child. Apparently, subprocess.call choses to keep the child attached to the original controlling terminal, so it does receive SIGINT.

I don't know if such behavior is documented. Generally it makes sense. Only deamons have the reason to dissociate themselves.

PS: *nix only. No idea how it works on Windows.

Upvotes: 6

Related Questions