我有一个 python 脚本,它启动多个进程。每个进程基本上只是调用一个 shell 脚本:
from multiprocessing import Process
import os
import logging
def thread_method(n = 4):
global logger
command = "~/Scripts/run.sh " + str(n) + " >> /var/log/mylog.log"
if (debug): logger.debug(command)
os.system(command)
我启动了其中几个线程,它们本来是要在后台运行的。我希望这些线程有一个超时时间,这样如果超过超时时间,它们就会被杀死:
t = []
for x in range(10):
try:
t.append(Process(target=thread_method, args=(x,) ) )
t[-1].start()
except Exception as e:
logger.error("Error: unable to start thread")
logger.error("Error message: " + str(e))
logger.info("Waiting up to 60 seconds to allow threads to finish")
t[0].join(60)
for n in range(len(t)):
if t[n].is_alive():
logger.info(str(n) + " is still alive after 60 seconds, forcibly terminating")
t[n].terminate()
问题是,在进程线程上调用 Terminate() 并不会终止启动的 run.sh 脚本 - 它会继续在后台运行,直到我从命令行强制终止它,或者它在内部完成。有没有办法让终止也杀死 os.system() 创建的子shell?
您应该使用一个事件来通知工作线程终止,运行子进程subprocess
模块,然后终止它Popen.terminate()
。呼唤Process.terminate()
不允许工人清理。看的文档Process.terminate().
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)