当前位置:首页 > PHP教程 > php高级应用 > 列表

PHP高级编程实例:编写守护进程

发布:smiling 来源: PHP粉丝网  添加日期:2021-04-10 15:50:07 浏览: 评论:0 

这篇文章主要介绍了PHP高级编程实例:编写守护进程,守护进程是脱离于终端并且在后台运行的进程,本文讲解使用PHP编写守护进程,并给出了代码实例,需要的朋友可以参考下

1.什么是守护进程

守护进程是脱离于终端并且在后台运行的进程。守护进程脱离于终端是为了避免进程在执行过程中的信息在任何终端上显示并且进程也不会被任何终端所产生的终端信息所打断。

例如 apache, nginx, mysql 都是守护进程

2.为什么开发守护进程

很多程序以服务形式存在,他没有终端或UI交互,它可能采用其他方式与其他程序交互,如TCP/UDP Socket, UNIX Socket, fifo。程序一旦启动便进入后台,直到满足条件他便开始处理任务。

3.何时采用守护进程开发应用程序

以我当前的需求为例,我需要运行一个程序,然后监听某端口,持续接受服务端发起的数据,然后对数据分析处理,再将结果写入到数据库中; 我采用ZeroMQ实现数据收发。

如果我不采用守护进程方式开发该程序,程序一旦运行就会占用当前终端窗框,还有受到当前终端键盘输入影响,有可能程序误退出。

4.守护进程的安全问题

我们希望程序在非超级用户运行,这样一旦由于程序出现漏洞被骇客控制,攻击者只能继承运行权限,而无法获得超级用户权限。

我们希望程序只能运行一个实例,不运行同事开启两个以上的程序,因为会出现端口冲突等等问题。

5.怎样开发守护进程

例 1. 守护进程例示

  1. <?php 
  2. class ExampleWorker extends Worker { 
  3.  
  4.  #public function __construct(Logging $logger) { 
  5.  # $this->logger = $logger; 
  6.  #} 
  7.  
  8.  #protected $logger; 
  9.  protected static $dbh; 
  10.  public function __construct() { 
  11.  
  12.  } 
  13.  public function run(){ 
  14.   $dbhost = '192.168.2.1';  // 数据库服务器 
  15.   $dbport = 3306; 
  16.    $dbuser = 'www';  // 数据库用户名 
  17.  $dbpass = 'qwer123';    // 数据库密码 
  18.   $dbname = 'example';  // 数据库名 
  19.  
  20.   self::$dbh = new PDO("mysql:host=$dbhost;port=$dbport;dbname=$dbname", $dbuser, $dbpass, array( 
  21.    /* PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'', */ 
  22.    PDO::MYSQL_ATTR_COMPRESS => true, 
  23.    PDO::ATTR_PERSISTENT => true 
  24.    ) 
  25.   ); 
  26.  
  27.  } 
  28.  protected function getInstance(){ 
  29.  return self::$dbh; 
  30.   } 
  31.  
  32. } 
  33.  
  34. /* the collectable class implements machinery for Pool::collect */ 
  35. class Fee extends Stackable { 
  36.  public function __construct($msg) { 
  37.   $trades = explode(",", $msg); 
  38.   $this->data = $trades; 
  39.   print_r($trades); 
  40.  } 
  41.  
  42.  public function run() { 
  43.   #$this->worker->logger->log("%s executing in Thread #%lu", __CLASS__, $this->worker->getThreadId() ); 
  44.  
  45.   try { 
  46.    $dbh = $this->worker->getInstance(); 
  47.      
  48.    $insert = "INSERT INTO fee(ticket, login, volume, `status`) VALUES(:ticket, :login, :volume,'N')"; 
  49.    $sth = $dbh->prepare($insert); 
  50.    $sth->bindValue(':ticket', $this->data[0]); 
  51.    $sth->bindValue(':login', $this->data[1]); 
  52.    $sth->bindValue(':volume', $this->data[2]); 
  53.    $sth->execute(); 
  54.    $sth = null; 
  55.      
  56.    /* ...... */ 
  57.      
  58.    $update = "UPDATE fee SET `status` = 'Y' WHERE ticket = :ticket and `status` = 'N'"; 
  59.    $sth = $dbh->prepare($update); 
  60.    $sth->bindValue(':ticket', $this->data[0]); 
  61.    $sth->execute(); 
  62.    //echo $sth->queryString; 
  63.    //$dbh = null; 
  64.   } 
  65.   catch(PDOException $e) { 
  66.    $error = sprintf("%s,%s\n", $mobile, $id ); 
  67.    file_put_contents("mobile_error.log", $error, FILE_APPEND); 
  68.   } 
  69.  } 
  70. } 
  71.  
  72. class Example { 
  73.  /* config */ 
  74.  const LISTEN = "tcp://192.168.2.15:5555"; 
  75.  const MAXCONN = 100; 
  76.  const pidfile = __CLASS__; 
  77.  const uid = 80; 
  78.  const gid = 80; 
  79.    
  80.  protected $pool = NULL; 
  81.  protected $zmq = NULL; 
  82.  public function __construct() { 
  83.   $this->pidfile = '/var/run/'.self::pidfile.'.pid'; 
  84.  } 
  85.  private function daemon(){ 
  86.   if (file_exists($this->pidfile)) { 
  87.    echo "The file $this->pidfile exists.\n"; 
  88.    exit(); 
  89.   } 
  90.     
  91.   $pid = pcntl_fork(); 
  92.   if ($pid == -1) { 
  93.     die('could not fork'); 
  94.   } else if ($pid) { 
  95.     // we are the parent 
  96.     //pcntl_wait($status); //Protect against Zombie children 
  97.    exit($pid); 
  98.   } else { 
  99.    // we are the child 
  100.    file_put_contents($this->pidfile, getmypid()); 
  101.    posix_setuid(self::uid); 
  102.    posix_setgid(self::gid); 
  103.    return(getmypid()); 
  104.   } 
  105.  } 
  106.  private function start(){ 
  107.   $pid = $this->daemon(); 
  108.   $this->pool = new Pool(self::MAXCONN, \ExampleWorker::class, []); 
  109.   $this->zmq = new ZMQSocket(new ZMQContext(), ZMQ::SOCKET_REP); 
  110.   $this->zmq->bind(self::LISTEN); 
  111.     
  112.   /* Loop receiving and echoing back */ 
  113.   while ($message = $this->zmq->recv()) { 
  114.    //print_r($message); 
  115.    //if($trades){ 
  116.      $this->pool->submit(new Fee($message)); 
  117.      $this->zmq->send('TRUE');  
  118.    //}else{ 
  119.    // $this->zmq->send('FALSE');  
  120.    //} 
  121.   } 
  122.   $pool->shutdown();  
  123.  } 
  124.  private function stop(){ 
  125.  
  126.   if (file_exists($this->pidfile)) { 
  127.    $pid = file_get_contents($this->pidfile); 
  128.    posix_kill($pid, 9);  
  129.    unlink($this->pidfile); 
  130.   } 
  131.  } 
  132.  private function help($proc){ 
  133.   printf("%s start | stop | help \n", $proc); 
  134.  } 
  135.  public function main($argv){ 
  136.   if(count($argv) < 2){ 
  137.    printf("please input help parameter\n"); 
  138.    exit(); 
  139.   } 
  140.   if($argv[1] === 'stop'){ 
  141.    $this->stop(); 
  142.   }else if($argv[1] === 'start'){ 
  143.    $this->start(); 
  144.   }else{ 
  145.    $this->help($argv[0]); 
  146.   } //www.phpfensi.com 
  147.  } 
  148. } 
  149.  
  150. $cgse = new Example(); 
  151. $cgse->main($argv); 

5.1. 程序启动

下面是程序启动后进入后台的代码

通过进程ID文件来判断,当前进程状态,如果进程ID文件存在表示程序在运行中,通过代码file_exists($this->pidfile)实现,但而后进程被kill需要手工删除该文件才能运行

  1. private function daemon(){ 
  2.   if (file_exists($this->pidfile)) { 
  3.    echo "The file $this->pidfile exists.\n"; 
  4.    exit(); 
  5.   } 
  6.     
  7.   $pid = pcntl_fork(); 
  8.   if ($pid == -1) { 
  9.     die('could not fork'); 
  10.   } else if ($pid) { 
  11.    // we are the parent 
  12.    //pcntl_wait($status); //Protect against Zombie children 
  13.    exit($pid); 
  14.   } else { 
  15.    // we are the child 
  16.    file_put_contents($this->pidfile, getmypid()); 
  17.    posix_setuid(self::uid); 
  18.    posix_setgid(self::gid); 
  19.    return(getmypid()); 
  20.   } 
  21.  } 

程序启动后,父进程会推出,子进程会在后台运行,子进程权限从root切换到指定用户,同时将pid写入进程ID文件。

5.2. 程序停止

程序停止,只需读取pid文件,然后调用posix_kill($pid, 9); 最后将该文件删除。

  1. private function stop(){ 
  2.  
  3.   if (file_exists($this->pidfile)) { 
  4.    $pid = file_get_contents($this->pidfile); 
  5.    posix_kill($pid, 9);  
  6.    unlink($this->pidfile); 
  7.   } 
  8.  } 

Tags: PHP守护进程

分享到: