PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

分享一个php处理信号的小例子

藏色散人
藏色散人 转载
2021-11-26 15:32:26 4026浏览

我们常用的信号

  • kill   sigterm sigkill【kill命令】

  • ctrl+c sigint【键盘发出】

  • reload sinhub【一般从终端发出】

  • ctrl+z sigstop 【键盘发出】

  • 定时器 sigalarm【一个进程只能有一个定时时间,多的会被新值覆盖】

sigkill和sinstop 在进行信号处理时,不能被忽略,(处理信号可以有忽略,执行默认 执行用户指定处理)

php信号小例子

<?php         function sighandler($signo){
                echo &#39;just for sigint&#39;,"\n";

        }

        function sighandler2($signo){

                echo &#39;just for sigquit&#39;,"\n";
        }
        declare(ticks=1);

        pcntl_signal(SIGINT,"sighandler");

        pcntl_signal(SIGQUIT,"sighandler2");
        for($i=1;$i<30;$i++){
                file_put_contents(&#39;/home/tbtest/out.txt&#39;,"$i"."秒\n");
                sleep(1);
        }

~

执行结果

root@lyh:/home/tbtest# php sigint.php 
^Cjust for sigint
^Cjust for sigint
^Cjust for sigint
just for sigquit
^Cjust for sigint
^Cjust for sigint
^Z
[1]+  Stopped                 php sigint.php
root@lyh:/home/tbtest# bg
[1]+ php sigint.php &
root@lyh:/home/tbtest# fg
php sigint.php
root@lyh:/home/tbtest# cat out.txt 
29秒
root@lyh:/home/tbtest#

关于捕捉sigquit

上面捕捉到了jsut for sigquit 是因为我另外起了一个终端,

root@lyh:~# ps -aux |grep php                                    
root     16385  0.5  1.9 377720 19468 pts/2    S+   15:09   0:00 php sigint.php
root     16390  0.0  0.0  11744   932 pts/0    S+   15:09   0:00 grep --color=auto php
root@lyh:~# kill -s sigquit 16385

ps:pcntl_signal_dispatch 比ticks效率会更高

推荐学习:《PHP视频教程

声明:本文转载于:segmentfault,如有侵犯,请联系admin@php.cn删除