python - 如何在 gnome 终端中终止子进程

标签 python linux subprocess kill

我有三个 *.py 脚本,命名为:

  • terminal_starter,
  • subprocess_in_terminal,
  • ctrlc_sender

分别用以下代码:

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)

我想终止 subprocess_in_terminal.py 但我做不到。

我在 Ubuntu 16.04 LTS 和 Python 2.7 上运行这些脚本。

如有任何帮助,我们将不胜感激。

最佳答案

似乎 gnome-terminal 从当前的父 shell 中分离出来并“采用”作为父 init 进程。因此,进程之间的父-祖先连接被打破,找到我们子进程的父进程和子进程成为一项不平凡的任务。

但是,如果 gnome-terminal 可以用“通用”shell 替换,那么我希望对 terminal_starter.py 和 ctrlc_sender.py 进行一些微小的更改会有所帮助:

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 将我们的进程指向进程的组长

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()

通过 psutil.Process 我们可以递归地杀死所有 child 。之后我们终于可以杀死父进程。

关于python - 如何在 gnome 终端中终止子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46060885/

相关文章:

带有字符串列表的 Python DataFrame 列不会展平

python - 如何测试 django 消息中是否存在某个级别

linux - 终止不响应 SIGINT、SIGQUIT 的终端连接进程

Python - 使用 Popen 执行具有多个条件的查找

python - 使用 Python 解析 XML 解析外部实体引用

python - 如何在 Discord.py 中获取消息的时间戳?

javascript - 如何将 exec 输出显示到文本区域

c - Linux 字符设备驱动程序返回骰子 - 通过 read() 命令访问

bash 脚本的 Python subprocess.check_call 不等待子进程完成

Python subprocess.Popen 不适用于 stdout