代码之家  ›  专栏  ›  技术社区  ›  Jackson_DKMG

python多处理:子进程终止,但pid保持不变

  •  0
  • Jackson_DKMG  · 技术社区  · 7 年前

    我一直在测试多个选项,但都没有用。

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

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

    断言错误:一个过程不能启动两次。

    我需要重新启动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
    

    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 回复  |  直到 7 年前
        1
  •  0
  •   M Dennis    7 年前

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

    您总是引用同一个进程,但正如错误消息所述,您不能两次执行一个进程

        2
  •  0
  •   wolfson109    7 年前