【发布时间】:2014-05-29 06:03:45
【问题描述】:
我试图在执行过程中终止进程,但未能阻止它。
我的线程是无限循环线程在收到终止信号之前不会终止
我只能通过终端上的 kill 命令终止
def signal_handler(*args):
print("Killed by user")
teardown()
sys.exit(0)
def install_signal():
for sig in (SIGABRT, SIGILL, SIGINT, SIGSEGV, SIGTERM):
signal(sig, signal_handler)
class Monitor(object):
...
def run(self):
"""Run the monitor thread
Add the tasks to threads list
"""
try:
threads = {
"streaming": Streaming(
self.args["rtsp_link"],
int(self.args["duration"]),
int(self.args["period"])
),
"telnet_vid": p,
"telnet_aud": c,
}
for sub_task in threads.values():
sub_task.setDaemon(True)
sub_task.start()
for sub_task in threads.values():
sub_task.join()
time.sleep(1)
logging.info("Completed Monitor Tasks")
except KeyboardInterrupt:
print("Ok ok, quitting")
sys.exit(1)
except BaseException as e:
print("Got BaseException")
traceback.print_exc(file=sys.stdout)
raise e
def main():
try:
install_signal()
monitor = Monitor('tests/test_configuration.txt')
monitor.run()
except KeyboardInterrupt:
print("Ok ok, quitting")
sys.exit(1)
如果我在join() 中添加超时,主线程将不会被阻塞,将在几秒钟内终止,并且不再接收键盘中断
我提到了这个blog
while len(running_threads) > 0 :
try:
print("To add join")
# Join all threads using a timeout so it doesn't block
# Filter out threads which have been joined or are None
running_threads = [t.join(1) for t in running_threads if t is not None and t.isAlive()]
except KeyboardInterrupt:
print("Ctrl+C received! Sending kill to threads!!!")
for t in running_threads:
t.kill_received = True
【问题讨论】:
-
将
timeout添加到sub_task.join()并调用is_alive()来查看线程是否结束。在 Python 2 上,thread.join()没有超时可能不会被信号中断。 -
嗨@J.F.Sebastian 我更新了帖子,它不起作用
-
t.join(1)总是返回None因此running_threads = [t.join(1) for ...]不正确 -
@J.F.Sebastian 为什么?你说添加一个
timeout加入,所以我添加了1秒加入。 -
思考为什么
running_threads = [None, None, None, ...]不是非常有用