我有许多用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。但是如果这个过程崩溃了,主人也会默默地退出。
是否可以防止此行为并使整个系统更加健壮?
答案 0 :(得分:0)
您正在父进程中创建新工作程序,而不是在子进程中创建。这是我使用的一些标准代码:
$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
}