简体   繁体   中英

python multiprocessing : child process terminated, but pid remains

I've been testing multiple options to no avail.

I have a Flask app running and allowing the user to start and stop a background function, within another process that is running until terminated by the 'stop' signal.

This is working, however the issue I'm facing is that the child process, despite having been terminated, still has a PID and an exit code (0, -15, -9 depending on what I tried).

As a result, the user cannot restart that function because it generates an:

AssertionError : You cannot start a process twice.

I need to restart the Flask app in order to start the background function again. Here is the code for the background function:

class background_function(Process):

  def __init__(self):
    Process.__init__(self)
    self.exit = Event()

  def shutdown(self):
    self.exit.set()


  def run(self):
      #some variables declared here, and a try/except to verify that the 
      #remote device is online (a pi zero, function is using the remote gpio)
   while not self.exit.is_set():
      #code

And the Flask route, triggered by a button click on the html page:

proc = background_function()

@app.route('/_run', methods=['GET'])
def run():
    if proc.pid is None:
        try:
            proc.start()
            sleep(2)

    if proc.is_alive():
        return('Active')

    else:
        proc.shutdown()
        sleep(0.1)
        return('FAILED')

    except Exception as e:
         print(e)
         proc.shutdown()


    else:
        p = psutil.Process(proc.pid)
        p.kill()
        return ('DISABLED')

Note that the psutil thing is my last attempt, and gives the exact same results that when using process.terminate(), or when the background function is a single function and not a class. I'm running out of ideas here, so any help or advice would be welcome.

The multiprocessing documentation states that Process.start "must be called at most once per process". If you wish to run the same function again, you need to create a new process object.

I think your background_function has to look like this:

class background_function(Process):

  def shutdown(self):
    self.exit.set()    

  def run(self):
    Process.__init__(self)
    self.exit = Event() 
      #some variables declared here, and a try/except to verify that the 
      #remote device is online (a pi zero, function is using the remote gpio)
    while not self.exit.is_set():
      #code

You refer always to the same process, but as the error message said you cannot execute a process twice

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM