【问题标题】:Daemonized PHP: master process exits when child one crashes守护进程 PHP:当子进程崩溃时主进程退出
【发布时间】:2012-10-26 11:05:11
【问题描述】:

我有一些用 PHP 编写的 linux 守护进程来做一些后台工作。 有一个“主”进程有时会通过pcntl_fork 生成工作进程并控制它们。

这是(相当简单的)代码:

private function SpawnWorker($realm, $parallelismKey)
{
  $pid = pcntl_fork();

  if ($pid)
  {
    $worker = DaemonInstance::Create($pid, $realm, $parallelismKey);
    $worker->Store();
    $this->workers[$pid] = $worker;
    return $worker;
  }

  else if ($pid == 0) //  we're in child process now
    return Daemon::REINCARNATE;

  else
    xechonl("#red#UNABLE TO SPAWN A WORKER ($realm, $parallelismKey)");

  return false;
}

在返回“reincarnate”值后,新的工作进程调用posix_setsid,它返回一个新的会话ID。但是如果这个进程崩溃了,主进程也会默默退出。

是否可以防止这种行为并使整个系统更加健壮?

【问题讨论】:

    标签: php linux daemon


    【解决方案1】:

    您是在父进程中创建一个新的工作者,而不是在子进程中。这是我使用的一些标准代码:

    $pid = pcntl_fork();
    if ($pid == -1) {
        // could not daemonize
        exit(1);
    } elseif ($pid > 0) {
        exit(0); // already daemonized (we are the parent process)
    } else {
        umask(0);
        $sid = posix_setsid();
        if ($sid < 0) {
            exit(1); // could not detach session id (could not create child)
        }
    
        // capture output and errors
        fclose(STDIN); fclose(STDOUT); fclose(STDERR);
        $STDIN = fopen('/dev/null', 'r');
        $STDOUT = fopen('/dev/null', 'wb');
        $STDERR = fopen('/dev/null', 'wb');
    
        // ADD CODE HERE
    

    }

    【讨论】:

      猜你喜欢
      • 2017-10-26
      • 1970-01-01
      • 2022-12-12
      • 2012-02-15
      • 2013-06-09
      • 2018-05-19
      • 1970-01-01
      • 1970-01-01
      • 2012-10-15
      相关资源
      最近更新 更多