I have three *.py scripts named as:
with the following code respectively:
terminal_starter.py
import subprocess
import os
p = subprocess.Popen(['gnome-terminal -e "python subprocess_in_terminal.py"'], shell=True)
gpid = os.getpgrp()
ppid = os.getpid()
p1 = subprocess.Popen(["python ctrlc_sender.py " + str(gpid) + " " + str(ppid)], shell=True)
while 1:
pass
subprocess_in_terminal.py
import time
while 1:
print "Subprocess in terminal."
time.sleep(1)
ctrlc_sender.py
import signal
import os
import sys
import time
gpid = sys.argv[1]
ppid = sys.argv[2]
for i in range(10):
print "Killer says: I will kill " + gpid + "and " + ppid
time.sleep(1)
os.killpg(int(gpid), signal.SIGTERM)
os.kill(int(ppid), signal.SIGTERM)
I want to kill subprocess_in_terminal.py but I am not able.
I am running these scripts on Ubuntu 16.04 LTS and Python 2.7.
Any help would be appreciated.
It seems that gnome-terminal detach itself from current parent shell and "adopt" as a parent init process. Thus the parent-ancestor connections between processes is broken and finding the parents and children of our subprocess become a non trivial task.
However if gnome-terminal could be replaced with a "general" shell then I hope that some minimal changes in terminal_starter.py and ctrlc_sender.py could be helpful:
terminal_starter.py
1 import subprocess
2 import os
3
4 p = subprocess.Popen(['python subprocess_in_terminal.py'],preexec_fn=os.setsid, shell=True)
5
6 gpid = os.getpgrp()
7 ppid = os.getpid()
8
9 p1 = subprocess.Popen(["python ctrlc_sender.py " + str(gpid) + " " + str(ppid)], shell=True)
10
11 while 1:
12
13 pass
preexec_fn=os.setsid point our process as a group leader of processes
ctrlc_sender.py
1 import signal
2 import os
3 import sys
4 import time
5
6 gpid = sys.argv[1]
7 ppid = sys.argv[2]
8
9 for i in range(10):
10 print "Killer says: I will kill " + gpid + " and " + ppid
11 time.sleep(1)
12
13
14 import psutil
15
16 paren_proc = psutil.Process(int(ppid))
17
18 for child_proc in parent_proc.children(recursive=True):
19 child_proc.kill()
20 parent_proc.kill()
Trough psutil.Process we could recursively kill all children. And after that we could finally kill parent process.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.