分享PHP守护进程类


Posted in PHP onDecember 30, 2015

用PHP实现的Daemon类。可以在服务器上实现队列或者脱离 crontab 的计划任务。 
使用的时候,继承于这个类,并重写 _doTask 方法,通过 main 初始化执行。

<?php
 
class Daemon {
 
  const DLOG_TO_CONSOLE = 1;
  const DLOG_NOTICE = 2;
  const DLOG_WARNING = 4;
  const DLOG_ERROR = 8;
  const DLOG_CRITICAL = 16;
 
  const DAPC_PATH = '/tmp/daemon_apc_keys';
 
  /**
   * User ID
   *
   * @var int
   */
  public $userID = 65534; // nobody
 
  /**
   * Group ID
   *
   * @var integer
   */
  public $groupID = 65533; // nobody
 
  /**
   * Terminate daemon when set identity failure ?
   *
   * @var bool
   * @since 1.0.3
   */
  public $requireSetIdentity = false;
 
  /**
   * Path to PID file
   *
   * @var string
   * @since 1.0.1
   */
  public $pidFileLocation = '/tmp/daemon.pid';
 
  /**
   * processLocation
   * 进程信息记录目录
   *
   * @var string
   */
  public $processLocation = '';
 
  /**
   * processHeartLocation
   * 进程心跳包文件
   *
   * @var string
   */
  public $processHeartLocation = '';
 
  /**
   * Home path
   *
   * @var string
   * @since 1.0
   */
  public $homePath = '/';
 
  /**
   * Current process ID
   *
   * @var int
   * @since 1.0
   */
  protected $_pid = 0;
 
  /**
   * Is this process a children
   *
   * @var boolean
   * @since 1.0
   */
  protected $_isChildren = false;
 
  /**
   * Is daemon running
   *
   * @var boolean
   * @since 1.0
   */
  protected $_isRunning = false;
 
  /**
   * Constructor
   *
   * @return void
   */
  public function __construct() {
 
    error_reporting(0);
    set_time_limit(0);
    ob_implicit_flush();
 
    register_shutdown_function(array(&$this, 'releaseDaemon'));
  }
 
  /**
   * 启动进程
   *
   * @return bool
   */
  public function main() {
 
    $this->_logMessage('Starting daemon');
 
    if (!$this->_daemonize()) {
      $this->_logMessage('Could not start daemon', self::DLOG_ERROR);
 
      return false;
    }
 
    $this->_logMessage('Running...');
 
    $this->_isRunning = true;
 
    while ($this->_isRunning) {
      $this->_doTask();
    }
 
    return true;
  }
 
  /**
   * 停止进程
   *
   * @return void
   */
  public function stop() {
 
    $this->_logMessage('Stoping daemon');
 
    $this->_isRunning = false;
  }
 
  /**
   * Do task
   *
   * @return void
   */
  protected function _doTask() {
    // override this method
  }
 
  /**
   * _logMessage
   * 记录日志
   *
   * @param string 消息
   * @param integer 级别
   * @return void
   */
  protected function _logMessage($msg, $level = self::DLOG_NOTICE) {
    // override this method
  }
 
  /**
   * Daemonize
   *
   * Several rules or characteristics that most daemons possess:
   * 1) Check is daemon already running
   * 2) Fork child process
   * 3) Sets identity
   * 4) Make current process a session laeder
   * 5) Write process ID to file
   * 6) Change home path
   * 7) umask(0)
   *
   * @access private
   * @since 1.0
   * @return void
   */
  private function _daemonize() {
 
    ob_end_flush();
 
    if ($this->_isDaemonRunning()) {
      // Deamon is already running. Exiting
      return false;
    }
 
    if (!$this->_fork()) {
      // Coudn't fork. Exiting.
      return false;
    }
 
    if (!$this->_setIdentity() && $this->requireSetIdentity) {
      // Required identity set failed. Exiting
      return false;
    }
 
    if (!posix_setsid()) {
      $this->_logMessage('Could not make the current process a session leader', self::DLOG_ERROR);
 
      return false;
    }
 
    if (!$fp = fopen($this->pidFileLocation, 'w')) {
      $this->_logMessage('Could not write to PID file', self::DLOG_ERROR);
      return false;
    } else {
      fputs($fp, $this->_pid);
      fclose($fp);
    }
 
    // 写入监控日志
    $this->writeProcess();
 
    chdir($this->homePath);
    umask(0);
 
    declare(ticks = 1);
 
    pcntl_signal(SIGCHLD, array(&$this, 'sigHandler'));
    pcntl_signal(SIGTERM, array(&$this, 'sigHandler'));
    pcntl_signal(SIGUSR1, array(&$this, 'sigHandler'));
    pcntl_signal(SIGUSR2, array(&$this, 'sigHandler'));
 
    return true;
  }
 
  /**
   * Cheks is daemon already running
   *
   * @return bool
   */
  private function _isDaemonRunning() {
 
    $oldPid = file_get_contents($this->pidFileLocation);
 
    if ($oldPid !== false && posix_kill(trim($oldPid),0))
    {
      $this->_logMessage('Daemon already running with PID: '.$oldPid, (self::DLOG_TO_CONSOLE | self::DLOG_ERROR));
 
      return true;
    }
    else
    {
      return false;
    }
  }
 
  /**
   * Forks process
   *
   * @return bool
   */
  private function _fork() {
 
    $this->_logMessage('Forking...');
 
    $pid = pcntl_fork();
 
    if ($pid == -1) {
      // 出错
      $this->_logMessage('Could not fork', self::DLOG_ERROR);
 
      return false;
    } elseif ($pid) {
      // 父进程
      $this->_logMessage('Killing parent');
 
      exit();
    } else {
      // fork的子进程
      $this->_isChildren = true;
      $this->_pid = posix_getpid();
 
      return true;
    }
  }
 
  /**
   * Sets identity of a daemon and returns result
   *
   * @return bool
   */
  private function _setIdentity() {
 
    if (!posix_setgid($this->groupID) || !posix_setuid($this->userID))
    {
      $this->_logMessage('Could not set identity', self::DLOG_WARNING);
 
      return false;
    }
    else
    {
      return true;
    }
  }
 
  /**
   * Signals handler
   *
   * @access public
   * @since 1.0
   * @return void
   */
  public function sigHandler($sigNo) {
 
    switch ($sigNo)
    {
      case SIGTERM:  // Shutdown
        $this->_logMessage('Shutdown signal');
        exit();
        break;
 
      case SIGCHLD:  // Halt
        $this->_logMessage('Halt signal');
        while (pcntl_waitpid(-1, $status, WNOHANG) > 0);
        break;
      case SIGUSR1:  // User-defined
        $this->_logMessage('User-defined signal 1');
        $this->_sigHandlerUser1();
        break;
      case SIGUSR2:  // User-defined
        $this->_logMessage('User-defined signal 2');
        $this->_sigHandlerUser2();
        break;
    }
  }
 
  /**
   * Signals handler: USR1
   * 主要用于定时清理每个进程里被缓存的域名dns解析记录
   *
   * @return void
   */
  protected function _sigHandlerUser1() {
    apc_clear_cache('user');
  }
 
  /**
   * Signals handler: USR2
   * 用于写入心跳包文件
   *
   * @return void
   */
  protected function _sigHandlerUser2() {
 
    $this->_initProcessLocation();
 
    file_put_contents($this->processHeartLocation, time());
 
    return true;
  }
 
  /**
   * Releases daemon pid file
   * This method is called on exit (destructor like)
   *
   * @return void
   */
  public function releaseDaemon() {
 
    if ($this->_isChildren && is_file($this->pidFileLocation)) {
      $this->_logMessage('Releasing daemon');
 
      unlink($this->pidFileLocation);
    }
  }
 
  /**
   * writeProcess
   * 将当前进程信息写入监控日志,另外的脚本会扫描监控日志的数据发送信号,如果没有响应则重启进程
   *
   * @return void
   */
  public function writeProcess() {
 
    // 初始化 proc
    $this->_initProcessLocation();
 
    $command = trim(implode(' ', $_SERVER['argv']));
 
    // 指定进程的目录
    $processDir = $this->processLocation . '/' . $this->_pid;
    $processCmdFile = $processDir . '/cmd';
    $processPwdFile = $processDir . '/pwd';
 
    // 所有进程所在的目录
    if (!is_dir($this->processLocation)) {
      mkdir($this->processLocation, 0777);
      chmod($processDir, 0777);
    }
 
    // 查询重复的进程记录
    $pDirObject = dir($this->processLocation);
    while ($pDirObject && (($pid = $pDirObject->read()) !== false)) {
      if ($pid == '.' || $pid == '..' || intval($pid) != $pid) {
        continue;
      }
 
      $pDir = $this->processLocation . '/' . $pid;
      $pCmdFile = $pDir . '/cmd';
      $pPwdFile = $pDir . '/pwd';
      $pHeartFile = $pDir . '/heart';
 
      // 根据cmd检查启动相同参数的进程
      if (is_file($pCmdFile) && trim(file_get_contents($pCmdFile)) == $command) {
        unlink($pCmdFile);
        unlink($pPwdFile);
        unlink($pHeartFile);
 
        // 删目录有缓存
        usleep(1000);
 
        rmdir($pDir);
      }
    }
 
    // 新进程目录
    if (!is_dir($processDir)) {
      mkdir($processDir, 0777);
      chmod($processDir, 0777);
    }
 
    // 写入命令参数
    file_put_contents($processCmdFile, $command);
    file_put_contents($processPwdFile, $_SERVER['PWD']);
 
    // 写文件有缓存
    usleep(1000);
 
    return true;
  }
 
  /**
   * _initProcessLocation
   * 初始化
   *
   * @return void
   */
  protected function _initProcessLocation() {
 
    $this->processLocation = ROOT_PATH . '/app/data/proc';
    $this->processHeartLocation = $this->processLocation . '/' . $this->_pid . '/heart';
  }
}
PHP 相关文章推荐
php 获取一个月第一天与最后一天的代码
May 16 PHP
深入php处理整数函数的详解
Jun 09 PHP
php不允许用户提交空表单(php空值判断)
Nov 12 PHP
CI框架中集成CKEditor编辑器的教程
Jun 09 PHP
php+ajax导入大数据时产生的问题处理
Jun 11 PHP
7个鲜为人知却非常实用的PHP函数
Jul 01 PHP
基于PHP代码实现中奖概率算法可用于刮刮卡、大转盘等抽奖算法
Dec 20 PHP
详解PHP的Yii框架的运行机制及其路由功能
Mar 17 PHP
PHP实现对二维数组某个键排序的方法
Sep 14 PHP
yii2.0整合阿里云oss删除单个文件的方法
Sep 19 PHP
PHP实现的无限分类类库定义与用法示例【基于thinkPHP】
Aug 06 PHP
实现php删除链表中重复的结点
Sep 27 PHP
如何写php守护进程(Daemon)
Dec 30 #PHP
PHP汉字转换拼音的函数代码
Dec 30 #PHP
使用PHP如何实现高效安全的ftp服务器(二)
Dec 30 #PHP
php获取当前页面完整URL地址
Dec 30 #PHP
详解WordPress中添加和执行动作的函数使用方法
Dec 29 #PHP
详解WordPress中创建和添加过滤器的相关PHP函数
Dec 29 #PHP
yii,CI,yaf框架+smarty模板使用方法
Dec 29 #PHP
You might like
一个查看session内容的函数
2006/10/09 PHP
PHP针对伪静态的注入总结【附asp与Python相关代码】
2017/08/01 PHP
PHP设计模式之数据访问对象模式(DAO)原理与用法实例分析
2019/12/12 PHP
对YUI扩展的Gird组件 Part-2
2007/03/10 Javascript
关于flash遮盖div浮动层的解决方法
2010/07/17 Javascript
无阻塞加载脚本分析[全]
2011/01/20 Javascript
javascript 拖动表格行实现代码
2011/05/05 Javascript
JS继承 笔记
2011/07/13 Javascript
JavaScript Array Flatten 与递归使用介绍
2011/10/30 Javascript
javascript 事件处理示例分享
2014/12/31 Javascript
JavaScript验证Email(3种方法)
2015/09/21 Javascript
jquery实现弹窗功能(窗口居中显示)
2017/02/27 Javascript
jQuery实现三级联动效果
2017/03/02 Javascript
详解vue-cli中配置sass
2017/06/21 Javascript
Vue中的数据监听和数据交互案例解析
2017/07/12 Javascript
详解基于DllPlugin和DllReferencePlugin的webpack构建优化
2018/06/28 Javascript
Vue 实现输入框新增搜索历史记录功能
2019/10/15 Javascript
微信小程序点击item使之滚动到屏幕中间位置
2020/03/25 Javascript
vue实现图片上传功能
2020/05/28 Javascript
Vue Elenent实现表格相同数据列合并
2020/11/30 Vue.js
[56:29]Secret vs Optic 2018国际邀请赛小组赛BO2 第一场 8.18
2018/08/19 DOTA
python对象及面向对象技术详解
2016/07/19 Python
Python中py文件转换成exe可执行文件的方法
2019/06/14 Python
Django 对IP访问频率进行限制的例子
2019/08/30 Python
python matplotlib拟合直线的实现
2019/11/19 Python
基于Tensorflow批量数据的输入实现方式
2020/02/05 Python
python如何建立全零数组
2020/07/19 Python
SVG实现多彩圆环倒计时效果的示例代码
2017/11/21 HTML / CSS
HearthSong官网:儿童户外玩具、儿童益智玩具
2017/10/16 全球购物
高中校园广播稿
2014/01/11 职场文书
科技开发中心办公室主任岗位责任制
2014/02/10 职场文书
消防安全月活动总结
2015/05/08 职场文书
php 解析非标准json、非规范json
2021/04/01 PHP
django如何自定义manage.py管理命令
2021/04/27 Python
理解python中装饰器的作用
2021/07/21 Python
springboot新建项目pom.xml文件第一行报错的解决
2022/01/18 Java/Android