PHP进程信号处理
程序员文章站
2022-07-12 11:17:55
...
<?php
while (1) {
echo "I am doing something important\n";
echo "If i am interruptted, the data will be corrupted\n";
echo "Be careful\n";
echo "\n\n";
sleep(5);
}
假设现在有以上这么一个PHP脚本,我们想要脚本在收到SIGINT、SIGTERM等进程信号时,输出一段信息并结束脚本,该如何实现呢?
使用pcntl_signal和pcntl_signal_dispatch函数即可(注意PHP需要安装pcntl扩展才能使用这两个函数),见代码:
<?php
/**
* 信号ID和信号名称对应关系,没注释掉的信号都是可以通过pcntl_signal函数注册的
*/
$GLOBALS['G_SIG_MAP'] = array(
1 => 'SIGHUP',
2 => 'SIGINT',
3 => 'SIGQUIT',
4 => 'SIGILL',
5 => 'SIGTRAP',
6 => 'SIGABRT',
7 => 'SIGEMT',
8 => 'SIGFPE',
//9 => 'SIGKILL',
10 => 'SIGBUS',
11 => 'SIGSEGV',
12 => 'SIGSYS',
13 => 'SIGPIPE',
14 => 'SIGALRM',
15 => 'SIGTERM',
16 => 'SIGURG',
//17 => 'SIGSTOP',
18 => 'SIGTSTP',
19 => 'SIGCONT',
20 => 'SIGCHLD',
21 => 'SIGTTIN',
22 => 'SIGTTOU',
23 => 'SIGIO',
24 => 'SIGXCPU',
25 => 'SIGXFSZ',
26 => 'SIGVTALRM',
27 => 'SIGPROF',
28 => 'SIGWINCH',
29 => 'SIGINFO',
30 => 'SIGUSR1',
31 => 'SIGUSR2',
);
/**
* 进程信号处理函数
* @param int $signo 信号ID
*/
function signalHandler($signo) {
if (isset($GLOBALS['G_SIG_MAP'][$signo])) {
echo "Caught signal {$GLOBALS['G_SIG_MAP'][$signo]}, exit\n";
} else {
echo "Caught unknown signal:$signo";
}
exit();
}
foreach ($GLOBALS['G_SIG_MAP'] as $id => $name) {
pcntl_signal($id, 'signalHandler');
}
while (1) {
echo "I am doing something important\n";
echo "If i am interruptted, the data will be corrupted\n";
echo "Be careful\n";
echo "\n\n";
pcntl_signal_dispatch(); // 此函数调用必须放在循环体内
sleep(5);
}
在linux shell中执行该脚本,然后使用kill -2 脚本进程ID
命令向进程发送信号,脚本正常输出信息并退出。
上一篇: 【Linux】进程信号
下一篇: linux信号(signal)详解.md