我使用的库有时会陷入无限循环。该库中的所有操作均被记录下来,并且我使用线程来检测何时使用库日志在无限循环内进行调用。在检测到循环之后,我需要向挂起的进程发送诸如KeyboardInterrupt
之类的信号,以终止当前的调用并清除内容,然后重做作业。这是我尝试过的代码:
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()
就会杀死它,显然这不是我想要的。有想法吗?
答案 0 :(得分:1)
在基于Unix的系统中,SIGINT
信号用来表明这一点。信号通过kill(2)
发送,在Python中显示为os.kill
,信号编号在signal
包中。
您的使用类似于:
from os import kill
from signal import SIGINT
kill(process.pid, SIGINT)