我在一个帖子中调用top
进程。
如何在其他过程完成后或在一段时间后杀死线程和顶级进程?
class ExternalProcess(threading.Thread):
def run(self):
os.system("top")
def main():
# run the thread and 'top' process here
# join all other threads
for thread in self.thread_list:
thread.join()
# stop the thread and 'top' process here
答案 0 :(得分:0)
如果您使用的是类Unix平台,可以使用ps -A
列出您的流程,请尝试以下操作:
import subprocess, signal
import os
def killproc(procname):
p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)
out, err = p.communicate()
for line in out.splitlines():
if procname in line:
pid = int(line.split(None, 1)[0])
os.kill(pid, signal.SIGKILL)
killproc('firefox') #this is an example
如果您不在unix中使用正确的命令而不是ps -A
答案 1 :(得分:0)
使用进程组来处理子进程,因此您可以向子进程发送信号kill。
导入操作系统 进口信号 导入子流程
class ExternalProcess(threading.Thread):
def run(self):
# The os.setsid() is passed in the argument preexec_fn so
# it's run after the fork() and before exec() to run the shell.
proc = subprocess.Popen("top", stdout=subprocess.PIPE, shell=True, preexec_fn=os.setsid)
os.killpg(proc.pid, signal.SIGTERM) # Send the signal to all the process groups
def main():
# run the thread and 'top' process here
# join all other threads
for thread in self.thread_list:
thread.join()
# stop the thread and 'top' process here