我正在编写一些用于测试多线程程序的代码(学生作业 - 可能是错误的),并希望能够检测到它们何时死锁.当正常运行时,程序会定期生成输出到stdout,这样就可以很简单:如果X秒没有输出,则将其删除并报告死锁.这是函数原型:
def run_with_watchdog(command, timeout):
"""Run shell command, watching for output. If the program doesn't
produce any output for <timeout> seconds, kill it and return 1.
If the program ends successfully, return 0."""
Run Code Online (Sandbox Code Playgroud)
我可以自己编写,但要做到这一点有点棘手,所以如果可能的话,我宁愿使用现有的代码.有人写过类似的东西?
好的,请看下面的解决方案 如果您正在做类似的事情,子进程模块也可能是相关的.