如何写php守护进程(Daemon)

前端之家收集整理的这篇文章主要介绍了如何写php守护进程(Daemon)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

守护进程(Daemon)是运行在后台的一种特殊进程。它独立于控制终端并且周期性地执行某种任务或等待处理某些发生的事件。守护进程是一种很有用的进程。PHP也可以实现守护进程的功能

一、基本概念

进程:每个进程都有一个父进程,子进程退出,父进程能得到子进程退出的状态。 进程组

每个进程都属于一个进程组,每个进程组都有一个进程组号,该号等于该进程组组长的PID

二、守护编程要点

1. 在后台运行

为避免挂起控制终端将Daemon放入后台执行。方法是在进程中调用fork使父进程终止,让Daemon在子进程中后台执行。 if($pid=pcntl_fork()) exit(0);//是父进程,结束父进程,子进程继续 2. 脱离控制终端,登录会话和进程组 有必要先介绍一下Linux中的进程与控制终端,登录会话和进程组之间的关系:进程属于一个进程组,进程组号(GID)就是进程组长的进程号(PID)。登录会话可以包含多个进程组。这些进程组共享一个控制终端。这个控制终端通常是创建进程的登录终 端。 控制终端,登录会话和进程组通常是从父进程继承下来的。我们的目的就是要摆脱它们,使之不受它们的影响。方法是在第1点的基础上,调用setsid()使进程成为会话组长: posix_setsid(); 说明:当进程是会话组长时setsid()调用失败。但第一点已经保证进程不是会话组长。setsid()调用成功后,进程成为新的会话组长和新的进程组长,并与原来的登录会话和进程组脱离。由于会话过程对控制终端的独占性,进程同时与控制终端脱离。

禁止进程重新打开控制终端

现在,进程已经成为无终端的会话组长。但它可以重新申请打开一个控制终端。可以通过使进程不再成为会话组长来禁止进程重新打开控制终端: if($pid=pcntl_fork()) exit(0);//结束第一子进程,第二子进程继续(第二子进程不再是会话组长)

关闭打开的文件描述符

进程从创建它的父进程那里继承了打开的文件描述符。如不关闭,将会浪费系统资源,造成进程所在的文件系统无法卸下以及引起无法预料的错误。按如下方法关闭它们: fclose(STDIN),fclose(STDOUT),fclose(STDERR)关闭标准输入输出错误显示5. 改变当前工作目录 进程活动时,其工作目录所在的文件系统不能卸下。一般需要将工作目录改变到根目录。对于需要转储核心,写运行日志的进程将工作目录改变到特定目录如chdir("/") 6. 重设文件创建掩模 进程从创建它的父进程那里继承了文件创建掩模。它可能修改守护进程所创建的文件的存取位。为防止这一点,将文件创建掩模清除:umask(0); 7. 处理SIGCHLD信号 处理SIGCHLD信号并不是必须的。但对于某些进程,特别是服务器进程往往在请求到来时生成子进程处理请求。如果父进程不等待子进程结束,子进程将成为僵尸进程(zombie)从而占用系统资源。如果父进程等待子进程结束,将增加父进程的负担,影 响服务器进程的并发性能。在Linux下可以简单地将SIGCHLD信号的操作设为SIG_IGN。 signal(SIGCHLD,SIG_IGN); 这样,内核在子进程结束时不会产生僵尸进程。这一点与BSD4不同,BSD4下必须显式等待子进程结束才能释放僵尸进程。关于信号的问题请参考Linux 信号说明列表

三、实例

PHP;"> private $info_dir="/tmp";
private $pid_file="";
private $terminate=false; //是否中断
private $workers_count=0;
private $gc_enabled=null;
private $workers_max=8; //最多运行8个进程

public function __construct($is_sington=false,$user='nobody',$output="/dev/null"){

  1. $this->is_sington=$is_sington; //是否单例运行,单例运行会在tmp目录下建立一个唯一的PID
  2. $this->user=$user;//设置运行的<a href="/tag/yonghu/" target="_blank" class="keywords">用户</a> 默认情况下nobody
  3. $this->output=$output; //设置<a href="/tag/shuchu/" target="_blank" class="keywords">输出</a>的地方
  4. $this->checkPcntl();

}
//检查环境是否支持pcntl支持
public function checkPcntl(){
if ( ! function_exists('pcntl_signal_dispatch')) {
// PHP < 5.3 uses ticks to handle signals instead of pcntl_signal_dispatch
// call sighandler only every 10 ticks
declare(ticks = 10);
}

  1. // Make sure PHP has support for pcntl
  2. if ( ! function_exists('pcntl_signal')) {
  3. $message = 'PHP does not appear to be compiled with the PCNTL extension. This is neccesary for daemonization';
  4. $this->_log($message);
  5. throw new Exception($message);
  6. }
  7. //信号处理
  8. pcntl_signal(SIGTERM,array(__CLASS__,"signalHandler"),false);
  9. pcntl_signal(SIGINT,false);
  10. pcntl_signal(SIGQUIT,false);
  11. // Enable <a href="/tag/PHP/" target="_blank" class="keywords">PHP</a> 5.3 garbage collection
  12. if (function_exists('gc_enable'))
  13. {
  14. gc_enable();
  15. $this->gc_enabled = gc_enabled();
  16. }

}

// daemon化程序
public function daemonize(){

  1. global $stdin,$stdout,$stderr;
  2. global $argv;
  3. set_time_limit(0);
  4. // 只允许在cli下面运行
  5. if (<a href="/tag/PHP/" target="_blank" class="keywords">PHP</a>_sapi_name() != "cli"){
  6. die("only run in command line mode\n");
  7. }
  8. // 只能单例运行
  9. if ($this->is_sington==true){
  10. $this->pid_file = $this->info_dir . "/" .__CLASS__ . "_" . substr(basename($argv[0]),-4) . ".pid";
  11. $this->checkPidfile();
  12. }
  13. umask(0); //把<a href="/tag/wenjian/" target="_blank" class="keywords">文件</a>掩码清0
  14. if (pcntl_fork() != 0){ //是父进程,父进程<a href="/tag/tuichu/" target="_blank" class="keywords">退出</a>
  15. exit();
  16. }
  17. posix_setsid();//设置新会话组长,脱离终端
  18. if (pcntl_fork() != 0){ //是第一子进程,结束第一子进程
  19. exit();
  20. }
  21. chdir("/"); //改变工作目录
  22. $this->setUser($this->user) or die("cannot change owner");
  23. //<a href="/tag/guanbi/" target="_blank" class="keywords">关闭</a>打开的<a href="/tag/wenjian/" target="_blank" class="keywords">文件</a>描述符
  24. fclose(STDIN);
  25. fclose(STDOUT);
  26. fclose(STDERR);
  27. $stdin = fopen($this->output,'r');
  28. $stdout = fopen($this->output,'a');
  29. $stderr = fopen($this->output,'a');
  30. if ($this->is_sington==true){
  31. $this->createPidfile();
  32. }

}
//--检测pid是否已经存在
public function checkPidfile(){

  1. if (!file_exists($this->pid_file)){
  2. return true;
  3. }
  4. $pid = file_get_contents($this->pid_file);
  5. $pid = intval($pid);
  6. if ($pid > 0 && posix_kill($pid,0)){
  7. $this->_log("the daemon process is already started");
  8. }
  9. else {
  10. $this->_log("the daemon proces end abnormally,please check pidfile " . $this->pid_file);
  11. }
  12. exit(1);

}
//----创建pid
public function createPidfile(){

  1. if (!is_dir($this->info_dir)){
  2. mkdir($this->info_dir);
  3. }
  4. $fp = fopen($this->pid_file,'w') or die("cannot create pid file");
  5. fwrite($fp,posix_getpid());
  6. fclose($fp);
  7. $this->_log("create pid file " . $this->pid_file);

}

//设置运行的用户
public function setUser($name){

  1. $result = false;
  2. if (empty($name)){
  3. return true;
  4. }
  5. $user = posix_getpwnam($name);
  6. if ($user) {
  7. $uid = $user['uid'];
  8. $gid = $user['gid'];
  9. $result = posix_setuid($uid);
  10. posix_setgid($gid);
  11. }
  12. return $result;

}
//信号处理函数
public function signalHandler($signo){

  1. switch($signo){
  2. //<a href="/tag/yonghu/" target="_blank" class="keywords">用户</a><a href="/tag/zidingyi/" target="_blank" class="keywords">自定义</a>信号
  3. case SIGUSR1: //busy
  4. if ($this->workers_count @H_<a href="/tag/404/" target="_blank" class="keywords">404</a>_30@workers_max){
  5. $pid = pcntl_fork();
  6. if ($pid > 0){
  7. $this->workers_count ++;
  8. }
  9. }
  10. break;
  11. //子进程结束信号
  12. case SIGCHLD:
  13. while(($pid=pcntl_waitpid(-1,$status,WNOHANG)) > 0){
  14. $this->workers_count --;
  15. }
  16. break;
  17. //中断进程
  18. case SIGTERM:
  19. case SIGHUP:
  20. case SIGQUIT:
  21. $this->terminate = true;
  22. break;
  23. default:
  24. return false;
  25. }

}
/*
开始开启进程
$count 准备开启的进程数
/
public function start($count=1){

  1. $this->_log("daemon process is running now");
  2. pcntl_signal(SIGCHLD,false); // if worker die,minus children num
  3. while (true) {
  4. if (function_exists('pcntl_signal_dispatch')){
  5. pcntl_signal_dispatch();
  6. }
  7. if ($this->terminate){
  8. break;
  9. }
  10. $pid=-1;
  11. if($this->workers_count<$count){
  12. $pid=pcntl_fork();
  13. }
  14. if($pid>0){
  15. $this->workers_count++;
  16. }elseif($pid==0){
  17. // 这个符号表示恢复系统对信号的默认处理
  18. pcntl_signal(SIGTERM,SIG_DFL);
  19. pcntl_signal(SIGCHLD,SIG_DFL);
  20. if(!empty($this->jobs)){
  21. while($this->jobs['runtime']){
  22. if(empty($this->jobs['argv'])){
  23. call_user_func($this->jobs['function'],$this->jobs['argv']);
  24. }else{
  25. call_user_func($this->jobs['function']);
  26. }
  27. $this->jobs['runtime']--;
  28. sleep(2);
  29. }
  30. exit();
  31. }
  32. return;
  33. }else{
  34. sleep(2);
  35. }
  36. }
  37. $this->mainQuit();
  38. exit(0);

}

//整个进程退出
public function mainQuit(){

  1. if (file_exists($this->pid_file)){
  2. unlink($this->pid_file);
  3. $this->_log("delete pid file " . $this->pid_file);
  4. }
  5. $this->_log("daemon process exit now");
  6. posix_kill(0,SIGKILL);
  7. exit(0);

}

// 添加工作实例,目前只支持单个job工作
public function setJobs($jobs=array()){

  1. if(!isset($jobs['argv'])||empty($jobs['argv'])){
  2. $jobs['argv']="";
  3. }
  4. if(!isset($jobs['runtime'])||empty($jobs['runtime'])){
  5. $jobs['runtime']=1;
  6. }
  7. if(!isset($jobs['function'])||empty($jobs['function'])){
  8. $this->log("你必须<a href="/tag/tianjia/" target="_blank" class="keywords">添加</a>运行的<a href="/tag/hanshu/" target="_blank" class="keywords">函数</a>!");
  9. }
  10. $this->jobs=$jobs;

}
//日志处理
private function _log($message){
printf("%s\t%d\t%d\t%s\n",date("c"),posix_getpid(),posix_getppid(),$message);
}

}

//调用方法1
$daemon=new DaemonCommand(true);
$daemon->daemonize();
$daemon->start(2);//开启2个子进程工作
work();

//调用方法2
$daemon=new DaemonCommand(true);
$daemon->daemonize();
$daemon->addJobs(array('function'=>'work','argv'=>'','runtime'=>1000));//function 要运行的函数,argv运行函数的参数,runtime运行的次数
$daemon->start(2);//开启2个子进程工作

//具体功能的实现
function work(){
echo "测试1";
}
?>

以上就是关于PHP守护进程的相关介绍,希望对大家的学习有所帮助。

猜你在找的PHP相关文章