Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill a subprocess initiated by a different function in the same class

I want to kill a process from another function in the class attending to the fact that it was initiated by another function. Here's an example:

 import time

 class foo_class:
    global foo_global
    def foo_start(self):
        import subprocess
        self.foo_global =subprocess.Popen(['a daemon service'])

    def foo_stop(self):
        self.foo_start.foo_global.kill()
        self.foo_start.foo_global.wait()


foo_class().foo_start()
time.sleep(5)
foo_class().foo_stop()

How should I define foo_stop?

like image 786
user3184086 Avatar asked Jan 11 '14 02:01

user3184086


People also ask

How do I get rid of subprocess Popen?

Both kill or terminate are methods of the Popen object. On macOS and Linux, kill sends the signal signal. SIGKILL to the process and terminate sends signal. SIGTERM .

What is subprocess Popen?

The subprocess module defines one class, Popen and a few wrapper functions that use that class. The constructor for Popen takes arguments to set up the new process so the parent can communicate with it via pipes. It provides all of the functionality of the other modules and functions it replaces, and more.


1 Answers

jterrace code works. If you don't want it to start when you initialize, just call Popen in a separate function and pass nothing to the init function

import subprocess 
import time

class foo_class(object):
    def __init__(self):
        pass

    def start(self):
        self.foo = subprocess.Popen(['a daemon service'])

    def stop(self):
        self.foo.kill()
        self.foo.wait() #don't know if this is necessary?

    def restart(self):
        self.start()


foo = foo_class()
foo.start()
time.sleep(5)
foo.stop()
like image 115
jwillis0720 Avatar answered Oct 12 '22 17:10

jwillis0720