【问题标题】:python multiprocessing : child process terminated, but pid remainspython multiprocessing:子进程终止,但pid仍然存在
【发布时间】:2017-09-19 14:44:13
【问题描述】:

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

我有一个 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

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

【问题讨论】:

  • 我认为你必须重新初始化进程。您在这里总是使用相同的流程:Process.__init__(self)。我觉得这个应该放在run
  • 哈。谢谢......我已经阅读了文档和“每个进程最多只能调用一次”,但认为在终止进程后它将被“重置”。我很确定这是一个愚蠢的错误:@
  • 好的,所以我重新测试并管理了它的工作。除了 M Dennis 的解决方案之外,我还必须在 Flask 路由的 def run() 中将 proc global global proc 重新声明为 proc = background_function()。我还必须将super().__init__() 添加到班级的def __init__(self)

标签: python flask multiprocessing


【解决方案1】:

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

    multiprocessing documentation 声明 Process.start “每个进程最多只能调用一次”。如果你想再次运行相同的函数,你需要创建一个新的进程对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 2017-07-24
      • 2011-12-22
      • 2011-02-05
      相关资源
      最近更新 更多