4
votes

How do I send a Ctrl-C to process or kill process with child processes?

Example of my code (python 2.7):

# --*-- coding: utf-8 --*--
import subprocess
import os
import signal

proc = subprocess.Popen(['ping localhost'],shell=True,stdout=subprocess.PIPE)
print proc.pid

a = raw_input()
os.killpg(proc.pid, signal.SIGTERM)

I see next processes when I run program:

user   16078  0.0  0.0   4476   916 pts/6    S+   14:41   0:00 /bin/sh -c ping localhost
user   16079  0.0  0.0   8628  1908 pts/6    S+   14:41   0:00 ping localhost

Program output:

16078

After raw_input:

Traceback (most recent call last):
  File "subproc2.py", line 10, in <module>
    os.killpg(proc.pid, signal.SIGTERM)
OSError: [Errno 3] No such process

I want kill process pid 16078 and pid 16079.

How would I do this and what the bug in program? Appreciate the help.

1

1 Answers

5
votes

How would I do this and what the bug in program?

If you want to kill all processes which includes in process group then you should use parent process id. Like that:

os.killpg(os.getpid(), signal.SIGTERM)

If you want to kill only one child process then use this:

os.kill(proc.pid, signal.SIGTERM)