首页 > 解决方案 > 子进程似乎挂起等待另一个结束

问题描述

我有一些这样的python代码:

def kill_something():
    # the kill command never stop.
    p = subprocess.Popen(self.kill_command, executable="/bin/bash", shell=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    (out, error) = p.communicate()
    # record error message if something wrong happened.
    ...

def check():
    # If not sleep here, the check process has a high opportunity to hang and wait the end of the above kill process.
    # time.sleep(2)
    # check the above kill command start successfully or not.
    command = "ps aux|grep kill_command|grep -v grep"
    p = subprocess.Popen(command, executable="/bin/bash", shell=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    (out, error) = p.communicate()
    ...

def do():
    thread = threading.Thread(target=kill_something, args=())
    thread.start()
    check()
    return

检查过程很有可能会挂起以等待终止过程结束,然后它才能完成。有时检查进程会很快结束,让 kill 进程单独运行,这是预期的行为。

在我看来,thread.start()之后thread中的kill进程与check方法中的进程无关,为什么check进程挂起等待kill进程结束然后才能完成?

如果我将 time.sleep(2) 添加到方法 check() 中,则检查可以很快成功。

标签: pythonsubprocess

解决方案


推荐阅读