分享PHP守護進程類_php技巧

來源:互聯網
上載者:User

用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';  }}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.