在php中,如果需要在某一段时间之内执行某一段逻辑代码的话,我们直接写定时脚本就可以了,但如果需要时时刻刻同步数据的话,这个时候再使用php定时脚本就显得有些吃力了,需要我们设置定时的脚本极期的短,短到秒扫表去执行,其实像这种实时同步数据的问题,我们还可以使用php的守护进程,也是我最近刚刚接触到的,说得直白一些,php守护进程就是一个死循环,比如我们要扫一个表,只要不触发停止命令,它是从不停歇的一直在执行某个逻辑段。,也就是我们可以在linux端后台一直执行某个程序逻辑段,守护进程(Daemon)是运行在后台的一种特殊进程。它独立于控制终端并且周期性地执行某种任务或等待处理某些发生的事件。守护进程是一种很有用的进程。php也可以实现守护进程的功能,具体的可以上搜索引擎查找一下php守护进程。,下面来看一段php守护进程实例:,php守护进程在处理同步数据方面很方便,或者也可应用在有需要循环执行的程序上,目前对于php守护进程夏日博客也是一知半解,随着深入了解,会把笔记慢慢记上来。,

在php中,如果需要在某一段时间之内执行某一段逻辑代码的话,我们直接写定时脚本就可以了,但如果需要时时刻刻同步数据的话,这个时候再使用php定时脚本就显得有些吃力了,需要我们设置定时的脚本极期的短,短到秒扫表去执行,其实像这种实时同步数据的问题,我们还可以使用php的守护进程,也是我最近刚刚接触到的,说得直白一些,php守护进程就是一个死循环,比如我们要扫一个表,只要不触发停止命令,它是从不停歇的一直在执行某个逻辑段。

也就是我们可以在linux端后台一直执行某个程序逻辑段,守护进程(Daemon)是运行在后台的一种特殊进程。它独立于控制终端并且周期性地执行某种任务或等待处理某些发生的事件。守护进程是一种很有用的进程。php也可以实现守护进程的功能,具体的可以上搜索引擎查找一下php守护进程。

下面来看一段php守护进程实例:

  1. * 后台脚本控制类   
  2. */   
  3. class DaemonCommand{   
  4.      
  5.   private $info_dir="/tmp";   
  6.   private $pid_file="";   
  7.   private $terminate=false; //是否中断   
  8.   private $workers_count=0;   
  9.   private $gc_enabled=null;   
  10.   private $workers_max=8; //最多运行8个进程   
  11.      
  12.   public function __construct($is_sington=false,$user='nobody',$output="/dev/null"){   
  13.      
  14.       $this->is_sington=$is_sington//是否单例运行,单例运行会在tmp目录下建立一个唯一的PID   
  15.       $this->user=$user;//设置运行的用户 默认情况下nobody   
  16.       $this->output=$output//设置输出的地方   
  17.       $this->checkPcntl();   
  18.   }   
  19.   //检查环境是否支持pcntl支持   
  20.   public function checkPcntl(){   
  21.     if ( ! function_exists('pcntl_signal_dispatch')) {   
  22.       // PHP < 5.3 uses ticks to handle signals instead of pcntl_signal_dispatch   
  23.       // call sighandler only every 10 ticks   
  24.       declare(ticks = 10);   
  25.     }   
  26.      
  27.     // Make sure PHP has support for pcntl   
  28.     if ( ! function_exists('pcntl_signal')) {   
  29.       $message = 'PHP does not appear to be compiled with the PCNTL extension. This is neccesary for daemonization';   
  30.       $this->_log($message);   
  31.       throw new Exception($message);   
  32.     }   
  33.     //信号处理   
  34.     pcntl_signal(SIGTERM, array(__CLASS__"signalHandler"),false);   
  35.     pcntl_signal(SIGINT, array(__CLASS__"signalHandler"),false);   
  36.     pcntl_signal(SIGQUIT, array(__CLASS__"signalHandler"),false);   
  37.      
  38.     // Enable PHP 5.3 garbage collection   
  39.     if (function_exists('gc_enable'))   
  40.     {   
  41.       gc_enable();   
  42.       $this->gc_enabled = gc_enabled();   
  43.     }   
  44.   }   
  45.      
  46.   // daemon化程序   
  47.   public function daemonize(){   
  48.      
  49.     global $stdin$stdout$stderr;   
  50.     global $argv;   
  51.      
  52.     set_time_limit(0);   
  53.      
  54.     // 只允许在cli下面运行   
  55.     if (php_sapi_name() != "cli"){   
  56.       die("only run in command line mode\n");   
  57.     }   
  58.      
  59.     // 只能单例运行   
  60.     if ($this->is_sington==true){   
  61.      
  62.       $this->pid_file = $this->info_dir . "/" .__CLASS__ . "_" . substr(basename($argv[0]), 0, -4) . ".pid";   
  63.       $this->checkPidfile();   
  64.     }   
  65.      
  66.     umask(0); //把文件掩码清0   
  67.      
  68.     if (pcntl_fork() != 0){ //是父进程,父进程退出   
  69.       exit();   
  70.     }   
  71.   
  72.     posix_setsid();//设置新会话组长,脱离终端   
  73.     if (pcntl_fork() != 0){ //是第一子进程,结束第一子进程     
  74.       exit();   
  75.     }   
  76.      
  77.     chdir("/"); //改变工作目录   
  78.      
  79.     $this->setUser($this->user) or die("cannot change owner");   
  80.      
  81.     //关闭打开的文件描述符   
  82.     fclose(STDIN);   
  83.     fclose(STDOUT);   
  84.     fclose(STDERR);   
  85.      
  86.     $stdin = fopen($this->output, 'r');   
  87.     $stdout = fopen($this->output, 'a');   
  88.     $stderr = fopen($this->output, 'a');   
  89.      
  90.     if ($this->is_sington==true){   
  91.       $this->createPidfile();   
  92.     }   
  93.      
  94.   }   
  95.   //--检测pid是否已经存在   
  96.   public function checkPidfile(){   
  97.      
  98.     if (!file_exists($this->pid_file)){   
  99.       return true;   
  100.     }   
  101.     $pid = file_get_contents($this->pid_file);   
  102.     $pid = intval($pid);   
  103.     if ($pid > 0 && posix_kill($pid, 0)){   
  104.       $this->_log("the daemon process is already started");   
  105.     }   
  106.     else {   
  107.       $this->_log("the daemon proces end abnormally, please check pidfile " . $this->pid_file);   
  108.     }   
  109.     exit(1);   
  110.      
  111.   }   
  112.   //----创建pid   
  113.   public function createPidfile(){   
  114.      
  115.     if (!is_dir($this->info_dir)){   
  116.       mkdir($this->info_dir);   
  117.     }   
  118.     $fp = fopen($this->pid_file, 'w') or die("cannot create pid file");   
  119.     fwrite($fp, posix_getpid());   
  120.     fclose($fp);   
  121.     $this->_log("create pid file " . $this->pid_file);   
  122.   }   
  123.      
  124.   //设置运行的用户   
  125.   public function setUser($name){   
  126.      
  127.     $result = false;   
  128.     if (emptyempty($name)){   
  129.       return true;   
  130.     }   
  131.     $user = posix_getpwnam($name);   
  132.     if ($user) {   
  133.       $uid = $user['uid'];   
  134.       $gid = $user['gid'];   
  135.       $result = posix_setuid($uid);   
  136.       posix_setgid($gid);   
  137.     }   
  138.     return $result;   
  139.   }   
  140.   //信号处理函数   
  141.   public function signalHandler($signo){   
  142.      
  143.     switch($signo){   
  144.       //用户自定义信号   
  145.       case SIGUSR1: //busy   
  146.       if ($this->workers_count < $this->workers_max){   
  147.         $pid = pcntl_fork();   
  148.         if ($pid > 0){   
  149.           $this->workers_count ++;   
  150.         }   
  151.       }   
  152.       break;   
  153.       //子进程结束信号   
  154.       case SIGCHLD:   
  155.         while(($pid=pcntl_waitpid(-1, $status, WNOHANG)) > 0){   
  156.           $this->workers_count --;   
  157.         }   
  158.       break;   
  159.       //中断进程   
  160.       case SIGTERM:   
  161.       case SIGHUP:   
  162.       case SIGQUIT:   
  163.         $this->terminate = true;   
  164.       break;   
  165.       default:   
  166.       return false;   
  167.     }   
  168.      
  169.   }   
  170.   /**  
  171.   *开始开启进程  
  172.   *$count 准备开启的进程数  
  173.   */  
  174.   public function start($count=1){   
  175.      
  176.     $this->_log("daemon process is running now");   
  177.     pcntl_signal(SIGCHLD, array(__CLASS__"signalHandler"),false); // if worker die, minus children num   
  178.     while (true) {   
  179.       if (function_exists('pcntl_signal_dispatch')){  
  180.         pcntl_signal_dispatch();   
  181.       }   
  182.   
  183.       if ($this->terminate){   
  184.         break;   
  185.       }   
  186.       $pid=-1;   
  187.       if($this->workers_count<$count){   
  188.         $pid=pcntl_fork();   
  189.       }   
  190.      
  191.       if($pid>0){  
  192.         $this->workers_count++;   
  193.       }elseif($pid==0){   
  194.      
  195.         // 这个符号表示恢复系统对信号的默认处理   
  196.         pcntl_signal(SIGTERM, SIG_DFL);   
  197.         pcntl_signal(SIGCHLD, SIG_DFL);   
  198.         if(!emptyempty($this->jobs)){   
  199.           while($this->jobs['runtime']){   
  200.             if(emptyempty($this->jobs['argv'])){   
  201.               call_user_func($this->jobs['function'],$this->jobs['argv']);   
  202.             }else{   
  203.               call_user_func($this->jobs['function']);   
  204.             }   
  205.             $this->jobs['runtime']--;   
  206.             sleep(2);   
  207.           }   
  208.           exit();   
  209.         }   
  210.         return;   
  211.       }else{  
  212.         sleep(2);   
  213.       }   
  214.     }  
  215.     $this->mainQuit();   
  216.     exit(0);  
  217.   }   
  218.      
  219.   //整个进程退出   
  220.   public function mainQuit(){   
  221.      
  222.     if (file_exists($this->pid_file)){   
  223.       unlink($this->pid_file);   
  224.       $this->_log("delete pid file " . $this->pid_file);   
  225.     }   
  226.     $this->_log("daemon process exit now");   
  227.     posix_kill(0, SIGKILL);   
  228.     exit(0);   
  229.   }   
  230.   
  231.   // 添加工作实例,目前只支持单个job工作   
  232.   public function setJobs($jobs=array()){   
  233.      
  234.     if(!isset($jobs['argv'])||emptyempty($jobs['argv'])){  
  235.       $jobs['argv']="";  
  236.     }   
  237.     if(!isset($jobs['runtime'])||emptyempty($jobs['runtime'])){  
  238.       $jobs['runtime']=1;   
  239.     }   
  240.      
  241.     if(!isset($jobs['function'])||emptyempty($jobs['function'])){  
  242.       $this->log("你必须添加运行的函数!");   
  243.     }   
  244.     $this->jobs=$jobs;   
  245.   }   
  246.   //日志处理   
  247.   private function _log($message){   
  248.     printf("%s\t%d\t%d\t%s\n"date("c"), posix_getpid(), posix_getppid(), $message);   
  249.   }   
  250.      
  251. }   
  252.      
  253. //调用方法1   
  254. $daemon=new DaemonCommand(true);   
  255. $daemon->daemonize();   
  256. $daemon->start(2);//开启2个子进程工作   
  257. work();   
  258.   
  259. //调用方法2   
  260. $daemon=new DaemonCommand(true);   
  261. $daemon->daemonize();   
  262. $daemon->addJobs(array('function'=>'work','argv'=>'','runtime'=>1000));//function 要运行的函数,argv运行函数的参数,runtime运行的次数   
  263. $daemon->start(2);//开启2个子进程工作   
  264. //www.xiariboke.net  
  265. //具体功能的实现   
  266. function work(){   
  267.    echo "测试1";   
  268. }   
  269. ?>  

php守护进程在处理同步数据方面很方便,或者也可应用在有需要循环执行的程序上,目前对于php守护进程夏日博客也是一知半解,随着深入了解,会把笔记慢慢记上来。

,

在php中,如果需要在某一段时间之内执行某一段逻辑代码的话,我们直接写定时脚本就可以了,但如果需要时时刻刻同步数据的话,这个时候再使用php定时脚本就显得有些吃力了,需要我们设置定时的脚本极期的短,短到秒扫表去执行,其实像这种实时同步数据的问题,我们还可以使用php的守护进程,也是我最近刚刚接触到的,说得直白一些,php守护进程就是一个死循环,比如我们要扫一个表,只要不触发停止命令,它是从不停歇的一直在执行某个逻辑段。

也就是我们可以在linux端后台一直执行某个程序逻辑段,守护进程(Daemon)是运行在后台的一种特殊进程。它独立于控制终端并且周期性地执行某种任务或等待处理某些发生的事件。守护进程是一种很有用的进程。php也可以实现守护进程的功能,具体的可以上搜索引擎查找一下php守护进程。

下面来看一段php守护进程实例:

  1. * 后台脚本控制类   
  2. */   
  3. class DaemonCommand{   
  4.      
  5.   private $info_dir="/tmp";   
  6.   private $pid_file="";   
  7.   private $terminate=false; //是否中断   
  8.   private $workers_count=0;   
  9.   private $gc_enabled=null;   
  10.   private $workers_max=8; //最多运行8个进程   
  11.      
  12.   public function __construct($is_sington=false,$user='nobody',$output="/dev/null"){   
  13.      
  14.       $this->is_sington=$is_sington//是否单例运行,单例运行会在tmp目录下建立一个唯一的PID   
  15.       $this->user=$user;//设置运行的用户 默认情况下nobody   
  16.       $this->output=$output//设置输出的地方   
  17.       $this->checkPcntl();   
  18.   }   
  19.   //检查环境是否支持pcntl支持   
  20.   public function checkPcntl(){   
  21.     if ( ! function_exists('pcntl_signal_dispatch')) {   
  22.       // PHP < 5.3 uses ticks to handle signals instead of pcntl_signal_dispatch   
  23.       // call sighandler only every 10 ticks   
  24.       declare(ticks = 10);   
  25.     }   
  26.      
  27.     // Make sure PHP has support for pcntl   
  28.     if ( ! function_exists('pcntl_signal')) {   
  29.       $message = 'PHP does not appear to be compiled with the PCNTL extension. This is neccesary for daemonization';   
  30.       $this->_log($message);   
  31.       throw new Exception($message);   
  32.     }   
  33.     //信号处理   
  34.     pcntl_signal(SIGTERM, array(__CLASS__"signalHandler"),false);   
  35.     pcntl_signal(SIGINT, array(__CLASS__"signalHandler"),false);   
  36.     pcntl_signal(SIGQUIT, array(__CLASS__"signalHandler"),false);   
  37.      
  38.     // Enable PHP 5.3 garbage collection   
  39.     if (function_exists('gc_enable'))   
  40.     {   
  41.       gc_enable();   
  42.       $this->gc_enabled = gc_enabled();   
  43.     }   
  44.   }   
  45.      
  46.   // daemon化程序   
  47.   public function daemonize(){   
  48.      
  49.     global $stdin$stdout$stderr;   
  50.     global $argv;   
  51.      
  52.     set_time_limit(0);   
  53.      
  54.     // 只允许在cli下面运行   
  55.     if (php_sapi_name() != "cli"){   
  56.       die("only run in command line mode\n");   
  57.     }   
  58.      
  59.     // 只能单例运行   
  60.     if ($this->is_sington==true){   
  61.      
  62.       $this->pid_file = $this->info_dir . "/" .__CLASS__ . "_" . substr(basename($argv[0]), 0, -4) . ".pid";   
  63.       $this->checkPidfile();   
  64.     }   
  65.      
  66.     umask(0); //把文件掩码清0   
  67.      
  68.     if (pcntl_fork() != 0){ //是父进程,父进程退出   
  69.       exit();   
  70.     }   
  71.   
  72.     posix_setsid();//设置新会话组长,脱离终端   
  73.     if (pcntl_fork() != 0){ //是第一子进程,结束第一子进程     
  74.       exit();   
  75.     }   
  76.      
  77.     chdir("/"); //改变工作目录   
  78.      
  79.     $this->setUser($this->user) or die("cannot change owner");   
  80.      
  81.     //关闭打开的文件描述符   
  82.     fclose(STDIN);   
  83.     fclose(STDOUT);   
  84.     fclose(STDERR);   
  85.      
  86.     $stdin = fopen($this->output, 'r');   
  87.     $stdout = fopen($this->output, 'a');   
  88.     $stderr = fopen($this->output, 'a');   
  89.      
  90.     if ($this->is_sington==true){   
  91.       $this->createPidfile();   
  92.     }   
  93.      
  94.   }   
  95.   //--检测pid是否已经存在   
  96.   public function checkPidfile(){   
  97.      
  98.     if (!file_exists($this->pid_file)){   
  99.       return true;   
  100.     }   
  101.     $pid = file_get_contents($this->pid_file);   
  102.     $pid = intval($pid);   
  103.     if ($pid > 0 && posix_kill($pid, 0)){   
  104.       $this->_log("the daemon process is already started");   
  105.     }   
  106.     else {   
  107.       $this->_log("the daemon proces end abnormally, please check pidfile " . $this->pid_file);   
  108.     }   
  109.     exit(1);   
  110.      
  111.   }   
  112.   //----创建pid   
  113.   public function createPidfile(){   
  114.      
  115.     if (!is_dir($this->info_dir)){   
  116.       mkdir($this->info_dir);   
  117.     }   
  118.     $fp = fopen($this->pid_file, 'w') or die("cannot create pid file");   
  119.     fwrite($fp, posix_getpid());   
  120.     fclose($fp);   
  121.     $this->_log("create pid file " . $this->pid_file);   
  122.   }   
  123.      
  124.   //设置运行的用户   
  125.   public function setUser($name){   
  126.      
  127.     $result = false;   
  128.     if (emptyempty($name)){   
  129.       return true;   
  130.     }   
  131.     $user = posix_getpwnam($name);   
  132.     if ($user) {   
  133.       $uid = $user['uid'];   
  134.       $gid = $user['gid'];   
  135.       $result = posix_setuid($uid);   
  136.       posix_setgid($gid);   
  137.     }   
  138.     return $result;   
  139.   }   
  140.   //信号处理函数   
  141.   public function signalHandler($signo){   
  142.      
  143.     switch($signo){   
  144.       //用户自定义信号   
  145.       case SIGUSR1: //busy   
  146.       if ($this->workers_count < $this->workers_max){   
  147.         $pid = pcntl_fork();   
  148.         if ($pid > 0){   
  149.           $this->workers_count ++;   
  150.         }   
  151.       }   
  152.       break;   
  153.       //子进程结束信号   
  154.       case SIGCHLD:   
  155.         while(($pid=pcntl_waitpid(-1, $status, WNOHANG)) > 0){   
  156.           $this->workers_count --;   
  157.         }   
  158.       break;   
  159.       //中断进程   
  160.       case SIGTERM:   
  161.       case SIGHUP:   
  162.       case SIGQUIT:   
  163.         $this->terminate = true;   
  164.       break;   
  165.       default:   
  166.       return false;   
  167.     }   
  168.      
  169.   }   
  170.   /**  
  171.   *开始开启进程  
  172.   *$count 准备开启的进程数  
  173.   */  
  174.   public function start($count=1){   
  175.      
  176.     $this->_log("daemon process is running now");   
  177.     pcntl_signal(SIGCHLD, array(__CLASS__"signalHandler"),false); // if worker die, minus children num   
  178.     while (true) {   
  179.       if (function_exists('pcntl_signal_dispatch')){  
  180.         pcntl_signal_dispatch();   
  181.       }   
  182.   
  183.       if ($this->terminate){   
  184.         break;   
  185.       }   
  186.       $pid=-1;   
  187.       if($this->workers_count<$count){   
  188.         $pid=pcntl_fork();   
  189.       }   
  190.      
  191.       if($pid>0){  
  192.         $this->workers_count++;   
  193.       }elseif($pid==0){   
  194.      
  195.         // 这个符号表示恢复系统对信号的默认处理   
  196.         pcntl_signal(SIGTERM, SIG_DFL);   
  197.         pcntl_signal(SIGCHLD, SIG_DFL);   
  198.         if(!emptyempty($this->jobs)){   
  199.           while($this->jobs['runtime']){   
  200.             if(emptyempty($this->jobs['argv'])){   
  201.               call_user_func($this->jobs['function'],$this->jobs['argv']);   
  202.             }else{   
  203.               call_user_func($this->jobs['function']);   
  204.             }   
  205.             $this->jobs['runtime']--;   
  206.             sleep(2);   
  207.           }   
  208.           exit();   
  209.         }   
  210.         return;   
  211.       }else{  
  212.         sleep(2);   
  213.       }   
  214.     }  
  215.     $this->mainQuit();   
  216.     exit(0);  
  217.   }   
  218.      
  219.   //整个进程退出   
  220.   public function mainQuit(){   
  221.      
  222.     if (file_exists($this->pid_file)){   
  223.       unlink($this->pid_file);   
  224.       $this->_log("delete pid file " . $this->pid_file);   
  225.     }   
  226.     $this->_log("daemon process exit now");   
  227.     posix_kill(0, SIGKILL);   
  228.     exit(0);   
  229.   }   
  230.   
  231.   // 添加工作实例,目前只支持单个job工作   
  232.   public function setJobs($jobs=array()){   
  233.      
  234.     if(!isset($jobs['argv'])||emptyempty($jobs['argv'])){  
  235.       $jobs['argv']="";  
  236.     }   
  237.     if(!isset($jobs['runtime'])||emptyempty($jobs['runtime'])){  
  238.       $jobs['runtime']=1;   
  239.     }   
  240.      
  241.     if(!isset($jobs['function'])||emptyempty($jobs['function'])){  
  242.       $this->log("你必须添加运行的函数!");   
  243.     }   
  244.     $this->jobs=$jobs;   
  245.   }   
  246.   //日志处理   
  247.   private function _log($message){   
  248.     printf("%s\t%d\t%d\t%s\n"date("c"), posix_getpid(), posix_getppid(), $message);   
  249.   }   
  250.      
  251. }   
  252.      
  253. //调用方法1   
  254. $daemon=new DaemonCommand(true);   
  255. $daemon->daemonize();   
  256. $daemon->start(2);//开启2个子进程工作   
  257. work();   
  258.   
  259. //调用方法2   
  260. $daemon=new DaemonCommand(true);   
  261. $daemon->daemonize();   
  262. $daemon->addJobs(array('function'=>'work','argv'=>'','runtime'=>1000));//function 要运行的函数,argv运行函数的参数,runtime运行的次数   
  263. $daemon->start(2);//开启2个子进程工作   
  264. //www.xiariboke.net  
  265. //具体功能的实现   
  266. function work(){   
  267.    echo "测试1";   
  268. }   
  269. ?>  

php守护进程在处理同步数据方面很方便,或者也可应用在有需要循环执行的程序上,目前对于php守护进程夏日博客也是一知半解,随着深入了解,会把笔记慢慢记上来。

最后修改:2025 年 09 月 10 日
如果觉得我的文章对你有用,请随意夸赞