Daemonized PHP:当一个孩子崩溃时,主进程退出

I have number of linux daemons written in PHP to do some background work. There is one "master" process which sometimes spawns worker processes via pcntl_fork and controls them.

Here is the (quite trivial) code:

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;
}

After returning with "reincarnate" value the new worker process calls posix_setsid, which returns a new session ID. But if this process crashes, the master one also silently exits.

Is it possible to prevent this behavior and make the entire system more robust?

You are creating a new worker in the parent process, not in a child process. Here's some standard code I use:

$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

}