使用PHP脚本来写Daemon程序(3)
5、为Worker编写信号控制,接受重启指令,类似于http restart graceful 指令。
最后,结合4和5两种方法,可以实现这样一个Daemon,如果配置文件发生了变化,他就会自动重启;如果接受到了用户的kill -1 pid 信号,也会重新启动。
代码如下:
<?php
declare( ticks = 1 );
// This case will check the config file regularly, if the config file changed, it will restart it self
// If you want to restart the daemon gracefully, give it a HUP signal
// by shiqiang<cocowool@gmail.com> at 2011-12-04
$init_md5 = md5_file( 'config.php');
// register signal handler
pcntl_signal( SIGALRM, "signal_handler", true );
pcntl_signal( SIGHUP, 'signal_handler', TRUE );
$job_flag = FALSE; //Job status flag, to justify if the job has been finished
$signal_flag = FALSE; //Signal status flag, to justify whether we received the kill -1 signal
while( 1 ){
$job_flag = FALSE; //Job status flag
print "Worker start running ... \n";
sleep(5);
print "Worker's task done ... \n";
$flag = TRUE; //Job status flag
AutoStart( $signal_flag );
}
function signal_handler( $signal ) {
global $job_flag;
global $signal_flag;
switch( $signal ){
case SIGQUIT:
print date('y-m-d H:i:s', time() ) . " Caught Signal : SIGQUIT - No : $signal \n";
exit(0);
break;
case SIGSTOP:
print date('y-m-d H:i:s', time() ) . " Caught Signal : SIGSTOP - No : $signal \n";
break;
case SIGHUP:
print date('y-m-d H:i:s', time() ) . " Caught Signal : SIGHUP - No : $signal \n";
if( $flag === TRUE ){
AutoStart( TRUE );
}else{
相关新闻>>
- 发表评论
-
- 最新评论 更多>>