0

我在使用 symfony 1.4 的 PHP 中遇到了一个奇怪的问题

我有一个启动多个工作人员的任务,有时,我需要停止所有工作人员(例如,在部署之后)。

我使用 start-stop-daemon 启动任务,我想通过向它发送信号 SIGINT 来停止它。

所以,这是我的代码:

protected function execute($arguments = array(), $options = array())
{
    $pid_arr = array();
    $thread = $this->forkChildren($arguments, $options, $options['nb_children']);

    if ($this->iAmParent())
    {
        declare(ticks = 1);
        pcntl_signal(SIGINT, array($this, 'signalHandler'));
        // Retrieve list of children PIDs
        $pid_arr = $this->getChildrenPids();
        // While there are still children processes
        while(count($pid_arr) > 0)
        {
            $myId = pcntl_waitpid(-1, $status);
            foreach($pid_arr as $key => $pid)
            {
                // If the stopped process is indeed a children of the parent process
                if ($myId == $pid)
                {
                    $this->removeChildrenPid($key);
                    // Recreate a child
                    $this->createNewChildren($arguments, $options, 1, $pid_arr);
                }
            }
            usleep(1000000);
            $pid_arr = $this->getChildrenPids();
        }
    }
    else
        $thread->run();
}

public function signalHandler($signal)
{
    echo "HANDLED SIGNAL $signal\n";
    foreach ($this->getChildrenPids() as $childrenPid)
    {
        echo "KILLING $childrenPid\n";
        posix_kill($childrenPid, $signal);
    }
    exit();
}

我所做的非常简单:我 fork,创建 N 个子进程,然后在父进程中添加一个 pcntl_signal 来捕获 SIGINT 信号。signalHanlder 函数检索子 pid 列表并向它们发送它刚刚收到的相同信号(即 SIGINT)。

问题是当我向父进程发送一个 INT 信号(通过 kill)时,不会调用 signalHandler 函数。我不明白为什么!

奇怪的是,当我在 cli 中启动任务并使用 Ctrl-C 时,会调用 signalHandler 函数并停止所有子进程。

那么,你明白为什么会这样吗?难道我做错了什么?

4

1 回答 1

0

好吧,算了,我刚问完问题就发现了问题:

我刚换

$myId = pcntl_waitpid(-1, $status);

经过

$myId = pcntl_waitpid(-1, $status, WNOHANG);

因为当然,该进程被挂起,等待其中一个孩子死去。

于 2014-01-21T10:29:16.000 回答