使用键盘中断python唤醒挂起进程
我使用的库有时会落入无限循环中。这个库中的所有操作都会被记录下来,我使用一个线程来检测调用何时进入无限循环(使用库日志)。在检测到循环后,我需要向挂起进程发送一个信号,如KeyboardInterrupt,以终止当前调用并清除所有内容,然后重新执行作业。以下是我尝试过的代码:使用键盘中断python唤醒挂起进程,python,multiprocessing,Python,Multiprocessing,我使用的库有时会落入无限循环中。这个库中的所有操作都会被记录下来,我使用一个线程来检测调用何时进入无限循环(使用库日志)。在检测到循环后,我需要向挂起进程发送一个信号,如KeyboardInterrupt,以终止当前调用并清除所有内容,然后重新执行作业。以下是我尝试过的代码: import threading import multiprocessing def worker(): job_not_done = True while job_not_done: t
import threading
import multiprocessing
def worker():
job_not_done = True
while job_not_done:
try:
call_a_library_function_that_may_fall_in_infinite_loop()
job_not_done = False
except KeyboardInterrupt:
do_some_clean_up()
print('Job interrupted, restarting ...')
def watcher(process):
infinite_loop = False
while not infinite_loop:
infinite_loop = detect_from_logs_if_inside_infinite_loop()
# send keyboardInterrupt signal to process
# process.sendSignal(KeyboardInterrupt) ??
p = multiprocessing.Process(target=starter)
p.start()
t = threading.Thread(target=watcher, args=(p,))
t.setDaemon(True)
t.start()
p.join()
我四处搜索,但找不到如何向子进程发送所需的信号。简单地调用process.terminate将杀死它,这显然不是我想要的。有什么想法吗?在基于Unix的系统中,SIGINT信号用于指示。信号通过kill2发送,kill2在Python中以os.kill的形式公开,信号包中包含信号号 您的使用情况如下所示:
from os import kill
from signal import SIGINT
kill(process.pid, SIGINT)
很抱歉,不要使用windows…您最好将重新启动代码移动到watcher中,即加入超时,如果没有完成,则终止。啊,windows在编程时会使一切变得复杂: