gpt4 book ai didi

python - 检查进程是否仍在运行

转载 作者:太空宇宙 更新时间:2023-11-04 04:33:44 25 4
gpt4 key购买 nike

我有以下问题:

我需要我的 Python 脚本运行 bash 脚本。如果 bash 脚本运行时间超过 10 秒,我需要终止它。这是我到目前为止所拥有的:

cmd = ["bash", "script.sh", self.get_script_path()]
process = subprocess.Popen(cmd)

time.sleep(10) # process running here...

procinfo = psutil.Process(process.pid)
children = procinfo.children(recursive=True)
for child in children:
os.kill(child.pid, signal.SIGKILL)

我担心的是这种情况:bash 脚本在 1 秒内完成,释放其 PID,系统将 PID 传递给另一个进程。 10 秒后,我杀死了 PID,我认为它属于我的脚本,但事实并非如此,我杀死了其他一些进程。该脚本需要以 root 身份运行,因为我需要其中的 chroot

有什么想法吗?

最佳答案

由于您已经在使用psutil我建议您将调用替换为 subprocess调用 psutil.Popen 的模块。该类具有与 subprocess.Popen 相同的接口(interface)但提供 psutil.Process 的所有功能.

另请注意psutil库已经预先检查 PID 重用,至少对于许多方法,包括 terminatekill (只需阅读 documentation for Process )。

这意味着以下代码:

cmd = ["bash", "script.sh", self.get_script_path()]
process = psutil.Popen(cmd)

time.sleep(10) # process running here...

children = process.children(recursive=True)
for child in children:
child.terminate() # try to close the process "gently" first
child.kill()

请注意 children 的文档说:

children(recursive=False)

Return the children of this process as a list of Process objects, preemptively checking whether PID has been reused.

总而言之,这意味着:

  1. 当您调用childrenpsutil库检查您是否想要正确进程的子进程,而不是碰巧具有相同 pid 的进程
  2. 当您调用terminate时或kill该库确保您杀死的是您的子进程,而不是具有相同 pid 的随机进程。

关于python - 检查进程是否仍在运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39188869/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com