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.

6
  • What does the output of ps look like? Commented Apr 9, 2012 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. Commented Apr 9, 2012 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). Commented Apr 9, 2012 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? Commented Apr 9, 2012 at 20:55
  • That means it really is still running. Commented Apr 9, 2012 at 21:00

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Great job my friend, simply change the shell=False, and the result.terminate() will terminate the process. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.