0

I have some python codes like this:

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

There will be a high opportunity the check process will hang to wait the kill process to end and then it can finish. And sometimes the check process can end quickly and let the kill process running alone which is the expected behavior.

In my point of view, after the thread.start() the kill process in thread has nothing to do with the process in check method, why the check process hangs to wait the kill process to end and then it can finish?

If i add the time.sleep(2) into the method check(), then the check can success quickly.

Ke Lu
  • 129
  • 3
  • 16
  • 1
    What are you actually doing? What is `self.kill_command`? If you want to kill a process, you can just use `os.kill()`. – AKX Oct 10 '18 at 08:25
  • Possible duplicate of [Blocking and Non Blocking subprocess calls](https://stackoverflow.com/questions/21936597/blocking-and-non-blocking-subprocess-calls) – roganjosh Oct 10 '18 at 08:26
  • In particular "You can make the Popen instance block by calling its wait or communicate method." – roganjosh Oct 10 '18 at 08:26
  • @AKX kill_command is a kind of process expected to run forever unless i manually stop it, it's nothing about killing a process. – Ke Lu Oct 10 '18 at 12:23
  • @roganjosh communicate is already called in my code. – Ke Lu Oct 10 '18 at 12:25
  • 1
    Yes, and the link I showed tells you that using `communicate` changes `Popen` from being non-blocking to blocking – roganjosh Oct 10 '18 at 12:25

0 Answers0