python多处理:子进程终止,但是pid仍然是

时间:2017-09-19 14:44:13

标签: python flask multiprocessing

我一直在测试多个选项无济于事。

我有一个Flask应用程序正在运行,允许用户在另一个正在运行的进程中启动和停止后台功能,直到被“stop”信号终止。

这是有效的,但是我面临的问题是子进程尽管已经终止,仍然有一个PID和一个退出代码(0,-15,-9取决于我尝试过的)。

因此,用户无法重新启动该功能,因为它会生成:

  

AssertionError:您无法启动两次进程。

我需要重新启动Flask应用才能再次启动后台功能。以下是后台功能的代码:

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

和Flask路线,由按钮点击html页面触发:

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')

请注意,psutil是我的最后一次尝试,并且提供与使用process.terminate()时相同的结果,或者当后台函数是单个函数而不是类时。我在这里没有想法,所以欢迎任何帮助或建议。

2 个答案:

答案 0 :(得分:0)

multiprocessing documentation表示每个进程最多只能调用一次Process.start""。如果您希望再次运行相同的功能,则需要创建一个新的过程对象。

答案 1 :(得分:0)

我认为您的background_function必须如此:

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

您始终引用相同的过程,但正如错误消息所述,您无法执行两次过程