【发布时间】:2020-07-14 18:59:07
【问题描述】:
我在 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)
但是,只有当前的终端进程会被关闭,而子进程不会。请让我了解我可能在哪里犯错。我想编写一个脚本来关闭与父终端关联的所有终端。
【问题讨论】:
标签: python python-3.x linux terminal