PHP pcntl_fork出來的子進程用到了信號量退出不成功

WBOY
發布: 2016-08-18 09:16:25
原創
1465 人瀏覽過

使用的測試程式碼如下:

<code><?php 

cli_set_process_title('test-semaphore');

$semid = sem_get(ftok(__FILE__, 'x'), 1);

function daemonize()
{
    umask(0);
    $pid = pcntl_fork();
    if (-1 === $pid) {
        throw new Exception('fork fail');
    } elseif ($pid > 0) {
        // 这里父进程可以退出
        exit(0);
    }
    
    if (-1 === posix_setsid()) {
        throw new Exception("setsid fail");
    }

    // 从这里开始信号量不删除就无法退出
    $pid = pcntl_fork();
    if (-1 === $pid) {
        throw new Exception("fork fail");
    } elseif (0 !== $pid) {
        // 子进程退出不成功
        exit(0);
    }
}

daemonize();
// 孙进程退出不成功

</code>
登入後複製
登入後複製

在命令列驗證:ps aux | grep test-semaphore 可以看到進程狀態是正常的(休眠狀態)

<code>xxx    115581  0.0  0.2 388532  7760 ?        Ss   11:33   0:00 test-semaphore
xxx    115582  0.0  0.1 388532  7584 ?        S    11:33   0:00 test-semaphore
</code>
登入後複製
登入後複製

在程式碼的任意地方使用sem_remove()或ipcrm指令都可以讓行程退出。

回覆內容:

使用的測試程式碼如下:

<code><?php 

cli_set_process_title('test-semaphore');

$semid = sem_get(ftok(__FILE__, 'x'), 1);

function daemonize()
{
    umask(0);
    $pid = pcntl_fork();
    if (-1 === $pid) {
        throw new Exception('fork fail');
    } elseif ($pid > 0) {
        // 这里父进程可以退出
        exit(0);
    }
    
    if (-1 === posix_setsid()) {
        throw new Exception("setsid fail");
    }

    // 从这里开始信号量不删除就无法退出
    $pid = pcntl_fork();
    if (-1 === $pid) {
        throw new Exception("fork fail");
    } elseif (0 !== $pid) {
        // 子进程退出不成功
        exit(0);
    }
}

daemonize();
// 孙进程退出不成功

</code>
登入後複製
登入後複製

在命令列驗證:ps aux | grep test-semaphore 可以看到進程狀態是正常的(休眠狀態)

<code>xxx    115581  0.0  0.2 388532  7760 ?        Ss   11:33   0:00 test-semaphore
xxx    115582  0.0  0.1 388532  7584 ?        S    11:33   0:00 test-semaphore
</code>
登入後複製
登入後複製

在程式碼的任意地方使用sem_remove()或ipcrm指令都可以讓行程退出。

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!