使用的测试代码如下:
<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 可以看到进程状态是正常的(休眠状态)
立即学习“PHP免费学习笔记(深入)”;
<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 可以看到进程状态是正常的(休眠状态)
立即学习“PHP免费学习笔记(深入)”;
<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怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号