1

I need to stop the service(runs at the background in another thread) that I issued through Popen in python after I got the result, but the following approach failed(just use ping for the sake of explanation):

class sample(threading.Thread):
  def __init__(self, command, queue):
    threading.Thread.__init__(self)
    self.command = command;
    self.queue = queue

  def run(self):
    result = Popen(self.command, shell=True, stdout=PIPE, stderr=STDOUT)    
    while True:
      output = result.stdout.readline()
      if not self.queue.empty():
        result.kill()
        break
      if output != "": 
        print output
      else:
        break

def main():
  q = Queue()
  command = sample("ping 127.0.0.1", q)
  command.start()
  time.sleep(10)
  q.put("stop!")
  command.join()

if __name__ == "__main__":
  main()

After running above program, when I pgrep for ping, it's still there. How can I kill the subprocess opened by Popen? Thanks.

PS: I also tried result.terminate(), but doesn't really solve the problem either.

Shang Wang
  • 24,909
  • 20
  • 73
  • 94
  • What does the output of `ps` look like? – Keith Apr 09 '12 at 20:41
  • @Keith: When I do ps aux | grep ping, it gives out the ping process running, if I don't use "kill", they are always there. – Shang Wang Apr 09 '12 at 20:43
  • It may be there, but what's it's status? I'm wondering if you just don't have to wait() on the subprocess (it's a zombie process). – Keith Apr 09 '12 at 20:47
  • @Keith: The status for the remaining thread is "S+", and it is created with another process when the command is issued. Do you think that it's the zombie process? How does that affect my process? – Shang Wang Apr 09 '12 at 20:55
  • That means it really is still running. – Keith Apr 09 '12 at 21:00
  • @Keith I'm sorry but the remaining process should have the status of "S" not "S+". After all, what does that imply? – Shang Wang Apr 09 '12 at 21:03

1 Answers1

3

You don't really need to run a subprocess from a thread. Try running the subprocess without a thread. Also, you specified shell=True, so it's running the command in a shell. So there are two new processes, the shell and the command. You can also remove the shell by making shell=False.

Keith
  • 42,110
  • 11
  • 57
  • 76
  • 1
    Great job my friend, simply change the shell=False, and the result.terminate() will terminate the process. Thanks. – Shang Wang Apr 09 '12 at 22:09