超时时杀死或终止子进程? [英] Kill or terminate subprocess when timeout?
问题描述
我想尽可能快地重复执行子过程.但是,有时该过程将花费很长时间,因此我想取消它. 我像下面这样使用signal.signal(...):
I would like to repeatedly execute a subprocess as fast as possible. However, sometimes the process will take too long, so I want to kill it. I use signal.signal(...) like below:
ppid=pipeexe.pid
signal.signal(signal.SIGALRM, stop_handler)
signal.alarm(1)
.....
def stop_handler(signal, frame):
print 'Stop test'+testdir+'for time out'
if(pipeexe.poll()==None and hasattr(signal, "SIGKILL")):
os.kill(ppid, signal.SIGKILL)
return False
,但是有时这段代码将尝试阻止下一轮执行. 停止test/home/lu/workspace/152/treefit/test2超时 /bin/sh:/home/lu/workspace/153/squib_driver:未找到---这是下一次执行;该程序错误地将其停止.
but sometime this code will try to stop the next round from executing. Stop test/home/lu/workspace/152/treefit/test2for time out /bin/sh: /home/lu/workspace/153/squib_driver: not found ---this is the next execution; the program wrongly stops it.
有人知道如何解决这个问题吗?我想停止不执行1秒的时间.sleep(n)经常等待n秒.我不希望它能在不到1秒的时间内执行
Does anyone know how to solve this? I want to stop in time not execute 1 second the time.sleep(n) often wait n seconds. I do not want that I want it can execute less than 1 second
推荐答案
您可以执行以下操作:
import subprocess as sub
import threading
class RunCmd(threading.Thread):
def __init__(self, cmd, timeout):
threading.Thread.__init__(self)
self.cmd = cmd
self.timeout = timeout
def run(self):
self.p = sub.Popen(self.cmd)
self.p.wait()
def Run(self):
self.start()
self.join(self.timeout)
if self.is_alive():
self.p.terminate() #use self.p.kill() if process needs a kill -9
self.join()
RunCmd(["./someProg", "arg1"], 60).Run()
想法是创建一个运行该命令的线程,并在超时超过某个合适的值(在这种情况下为60秒)时将其杀死.
The idea is that you create a thread that runs the command and to kill it if the timeout exceeds some suitable value, in this case 60 seconds.
这篇关于超时时杀死或终止子进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!