函数
pcntl_signal()是使用Ctrl-C(以及其他信号)中断脚本时的情况的答案.你必须注意文档.它说:
You must use the declare() statement to specify the locations in your program where callbacks are allowed to occur for the signal handler to function properly.
除其他事项外,declare()语句安装一个回调函数,通过调用函数pcntl_signal_dispatch()来处理自上次调用以来接收到的信号的调度,函数pcntl_signal_dispatch()又调用您安装的信号处理程序.
或者,当您认为它适合您的代码流时,您可以自己调用函数pcntl_signal_dispatch()(并且根本不使用declare(ticks = 1)).
这是一个使用declare(ticks = 1)的示例程序:
declare(ticks=1);
// Install the signal handlers
pcntl_signal(SIGHUP, 'handleSigHup');
pcntl_signal(SIGINT, 'handleSigInt');
pcntl_signal(SIGTERM, 'handleSigTerm');
while(true) {
echo 'loop';
sleep(1);
}
// Reset the signal handlers
pcntl_signal(SIGHUP, SIG_DFL);
pcntl_signal(SIGINT, SIG_DFL);
pcntl_signal(SIGTERM, SIG_DFL);
/**
* SIGHUP: the controlling pseudo or virtual terminal has been closed
*/
function handleSigHup()
{
echo("Caught SIGHUP, terminating.\n");
exit(1);
}
/**
* SIGINT: the user wishes to interrupt the process; this is typically initiated by pressing Control-C
*
* It should be noted that SIGINT is nearly identical to SIGTERM.
*/
function handleSigInt()
{
echo("Caught SIGINT, terminating.\n");
exit(1);
}
/**
* SIGTERM: request process termination
*
* The SIGTERM signal is a generic signal used to cause program termination.
* It is the normal way to politely ask a program to terminate.
* The shell command kill generates SIGTERM by default.
*/
function handleSigTerm()
{
echo("Caught SIGTERM, terminating.\n");
exit(1);
}