如何使用python终止在linux的父终端和“n”个子终端中运行的进程?

2024-06-08 15:54:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个Linux终端上运行一个python脚本“/main.py”,它会自动启动另外两个终端并在其中运行两个不同的代码

import os
import sys
import subprocess
import rospy
import psutil, sys
import signal

print(os.getpid())
arra = []
arra.append(os.getpid())
for i in range(2):
    if i == 0:     
        p = subprocess.Popen(['gnome-terminal', '--', 'roslaunch', 'ur5_notebook', 'main_r2_mt.launch', 'gui:=False'])
    if i > 0:
        p = subprocess.Popen(['gnome-terminal', '--', 'roslaunch', 'ur5_notebook', 'main_r2_mt.launch'])

    arra.append(p.pid)

rospy.sleep(20)

现在我还想杀死父终端和我启动的所有子终端。我首先用sys.exit()进行了一次尝试

print(os.getpid())
arra = []
arra.append(os.getpid())
for i in range(2):
    if i == 0:     
        p = subprocess.Popen(['gnome-terminal', '--', 'roslaunch', 'ur5_notebook', 'main_r2_mt.launch', 'gui:=False'], preexec_fn=os.setpgrp)
    if i > 0:
        p = subprocess.Popen(['gnome-terminal', '--', 'roslaunch', 'ur5_notebook', 'main_r2_mt.launch'], preexec_fn=os.setpgrp)
# rospy.sleep(50)
    arra.append(p.pid)
# print(list(os.getgroups))
rospy.sleep(20)

sys.exit()

但这只会终止当前/父端子,子端子仍处于活动状态

然后,我试图杀死单个进程id(PID),这是通过以下方法实现的

import os
import sys
import subprocess
import rospy
import psutil, sys
import signal

print(os.getpid())
arra = []
arra.append(os.getpid())
for i in range(2):
    if i == 0:     
        p = subprocess.Popen(['gnome-terminal', '--', 'roslaunch', 'ur5_notebook', 'main_r2_mt.launch', 'gui:=False'])
    if i > 0:
        p = subprocess.Popen(['gnome-terminal', '--', 'roslaunch', 'ur5_notebook', 'main_r2_mt.launch'])

    arra.append(p.pid)

rospy.sleep(20)

for i in reversed(arra):
     print(i)
     os.killpg(i, signal.SIGINT)

但仍然只有当前的终端进程关闭,而不是子进程。请给我一个我可能犯错误的地方。我想编写一个脚本,关闭与父终端关联的所有终端


Tags: import终端ifosmainsysterminalrospy
1条回答
网友
1楼 · 发布于 2024-06-08 15:54:27

您在使用代码时遇到问题,因为gnome-terminalgnome-terminal-server发送启动新终端的请求,然后它退出。您可以通过执行以下代码(代码的细微变化)来验证这一点,其中gnome-terminal在一个进程中调用,而xterm在另一个进程中调用:

import os
import sys
import subprocess
import psutil, sys
import signal
import time

print(os.getpid())

arra = []
#arra.append(os.getpid())

for i in range(2):
    if i == 0:     
        p = subprocess.Popen(['gnome-terminal', ' ', 'yes'])
        print ("gt: " + str(p.pid))
    if i > 0:
        p = subprocess.Popen(['xterm', '-hold', 'yes'])
        print("xt: " + str(p.pid))
    arra.append(p.pid)

for i in reversed(arra):
    print("next kill:" + str(i))
    time.sleep(60)
    os.kill(i, signal.SIGTERM)

如果在执行上述代码时在另一个shell中调用ps -e | grep gnome-terminal,您将看到gnome-terminal已失效,因此无法杀死它。另一方面,例如,如果您使用xterm,那么一切都会按照您的预期工作

样本输出:

gt: 26054
xt: 26055
next kill:26055

              -

$ ps -e | grep gnome-terminal
26054 pts/2    00:00:00 gnome-terminal <defunct>

因此,一个选项是使用xterm执行代码或具有类似行为的其他类型的终端

相关问题 更多 >