子进程似乎挂起,等待另一个结束

时间:2018-10-10 08:21:04

标签: python subprocess

我有一些像这样的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()之后,线程中的kill进程与check方法中的进程无关,为什么check进程挂起以等待kill进程结束然后可以完成?

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

0 个答案:

没有答案