为什么子进程无法成功杀死旧的进程?

时间:2015-02-13 03:35:35

标签: python subprocess kill terminate

我运行了一个程序test.py。 由于它经常崩溃,我导入subprocess以在停止时重新启动它。 有时我发现子进程无法成功重启。 因此,我强制程序每60分钟重新启动一次。 但我发现有时两个test.py处理同时运行。 我的代码有什么问题以及如何修复它? 我使用的是Windows 7操作系统。 Plz检查以下代码并提前感谢:

import subprocess
import time
from datetime import datetime

p = subprocess.Popen(['python.exe', r'D:\test.py'], shell=True)
minutes = 1
total_time = 0
while True:
    now = datetime.now()

    #periodly restart
    total_time += 1
    if total_time % 100 == 0:
        try:
            p.kill()
        except Exception as e:
            terminated = True
        finally:
            p = subprocess.Popen(['python.exe', r'D:\test.py'], shell=True)

    #check and restart if it stops
    try:
        terminated = p.poll()
    except Exception as e:
        terminated = True
    if terminated:
        p = subprocess.Popen(['python.exe', r'D:\test.py'], shell=True)
    time.sleep(minutes * 60)

1 个答案:

答案 0 :(得分:0)

虽然我对您的设计完全不同意,但具体问题在于:

except Exception as e:
        terminated = True
finally:
        p = subprocess.Popen(['python.exe', r'D:\test.py'], shell=True)

如果抛出Exception,您将terminated设置为true,然后立即重新启动子流程。然后,您稍后检查:

if terminated:
    p = subprocess.Popen(['python.exe', r'D:\test.py'], shell=True)

此时,terminatedtrue,因此它启动了一个新的子流程。但是,它已经在finally块中完成了。

真的,你应该做的就是在杀人尝试期间不再费心重启:

    try:
        p.kill()
    except Exception:
        # We don't care, just means it was already dead
        pass
    finally:
        # Either the process is dead, or we just killed it. Either way, need to restart
        terminated = True

然后您的if terminated子句将正确地重新启动该过程,您将不会有重复。