繁体   English   中英

python multiprocessing:子进程终止,但是pid仍然存在

[英]python multiprocessing : child process terminated, but pid remains

我一直在测试多个选项,但没有成功。

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

这是可行的,但是我面临的问题是子进程尽管已终止,但仍然具有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

然后通过html页面上的按钮触发Flask路线:

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()或后台函数是单个函数而不是类时完全相同。 我的想法不多了,因此欢迎您提供任何帮助或建议。

多处理文档指出Process.start“每个进程最多只能调用一次”。 如果希望再次运行相同的功能,则需要创建一个新的过程对象。

我认为您的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

您始终引用相同的进程,但是正如错误消息所言,您不能两次执行一个进程

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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