PHP pcntl_fork出来的子进程用到了信号量退出不成功

WBOY
发布: 2016-08-18 09:16:25
原创
1470 人浏览过

使用的测试代码如下:

<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学习者快速成长!