>  기사  >  백엔드 개발  >  PHP 고급 프로그래밍 예제: 데몬 process_php 기술 작성

PHP 고급 프로그래밍 예제: 데몬 process_php 기술 작성

WBOY
WBOY원래의
2016-05-16 20:36:431092검색

1. 데몬 프로세스란

데몬은 터미널과 분리되어 백그라운드에서 실행되는 프로세스입니다. 데몬 프로세스는 프로세스 실행 중 정보가 어떤 터미널에도 표시되지 않도록 터미널과 분리되어 있으며, 어떤 터미널에서 생성된 터미널 정보로 인해 프로세스가 중단되지 않습니다.

예를 들어 apache, nginx, mysql은 모두 데몬 프로세스입니다

2. 데몬 프로세스를 개발하는 이유

많은 프로그램이 서비스 형태로 존재합니다. 이러한 프로그램에는 터미널이나 UI 상호 작용이 없으며 TCP/UDP 소켓, UNIX 소켓, fifo 등 다른 방식으로 다른 프로그램과 상호 작용할 수 있습니다. 프로그램이 시작되면 백그라운드로 전환되어 조건이 충족될 때까지 작업 처리를 시작합니다.

3. 애플리케이션 개발을 위해 데몬 프로세스를 사용해야 하는 경우

현재 요구 사항을 예로 들어 보겠습니다. 프로그램을 실행한 다음 특정 포트를 수신하고 서버에서 시작된 데이터를 계속 수신한 다음 데이터를 분석하고 처리한 다음 결과를 데이터베이스에 기록해야 합니다. 저는 ZeroMQ를 사용하여 데이터 보내기 및 받기를 구현합니다.

이 프로그램을 개발하기 위해 데몬 프로세스를 사용하지 않으면 프로그램이 실행되면 현재 터미널 창 프레임을 차지하게 되며 현재 터미널 키보드 입력에 영향을 받을 수 있으며 프로그램이 실수로 종료될 수 있습니다.

4. 데몬 프로세스의 보안 문제

프로그램이 슈퍼유저가 아닌 권한으로 실행되어 일단 취약점으로 인해 해커가 프로그램을 제어하면 공격자는 실행 권한만 상속할 수 있고 슈퍼유저 권한을 얻을 수 없기를 바랍니다.

포트 충돌 등의 문제가 발생할 수 있으므로 프로그램이 하나의 인스턴스만 실행할 수 있고 동시에 두 개 이상의 프로그램을 실행하지 않기를 바랍니다.

5. 데몬 프로세스 개발 방법

예제 1. 데몬 프로세스 예시

<&#63;php
class ExampleWorker extends Worker {

 #public function __construct(Logging $logger) {
 # $this->logger = $logger;
 #}

 #protected $logger;
 protected static $dbh;
 public function __construct() {

 }
 public function run(){
  $dbhost = '192.168.2.1';  // 数据库服务器
  $dbport = 3306;
   $dbuser = 'www';  // 数据库用户名
 $dbpass = 'qwer123';    // 数据库密码
  $dbname = 'example';  // 数据库名

  self::$dbh = new PDO("mysql:host=$dbhost;port=$dbport;dbname=$dbname", $dbuser, $dbpass, array(
   /* PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'', */
   PDO::MYSQL_ATTR_COMPRESS => true,
   PDO::ATTR_PERSISTENT => true
   )
  );

 }
 protected function getInstance(){
 return self::$dbh;
  }

}

/* the collectable class implements machinery for Pool::collect */
class Fee extends Stackable {
 public function __construct($msg) {
  $trades = explode(",", $msg);
  $this->data = $trades;
  print_r($trades);
 }

 public function run() {
  #$this->worker->logger->log("%s executing in Thread #%lu", __CLASS__, $this->worker->getThreadId() );

  try {
   $dbh = $this->worker->getInstance();
   
   $insert = "INSERT INTO fee(ticket, login, volume, `status`) VALUES(:ticket, :login, :volume,'N')";
   $sth = $dbh->prepare($insert);
   $sth->bindValue(':ticket', $this->data[0]);
   $sth->bindValue(':login', $this->data[1]);
   $sth->bindValue(':volume', $this->data[2]);
   $sth->execute();
   $sth = null;
   
   /* ...... */
   
   $update = "UPDATE fee SET `status` = 'Y' WHERE ticket = :ticket and `status` = 'N'";
   $sth = $dbh->prepare($update);
   $sth->bindValue(':ticket', $this->data[0]);
   $sth->execute();
   //echo $sth->queryString;
   //$dbh = null;
  }
  catch(PDOException $e) {
   $error = sprintf("%s,%s\n", $mobile, $id );
   file_put_contents("mobile_error.log", $error, FILE_APPEND);
  }
 }
}

class Example {
 /* config */
 const LISTEN = "tcp://192.168.2.15:5555";
 const MAXCONN = 100;
 const pidfile = __CLASS__;
 const uid = 80;
 const gid = 80;
 
 protected $pool = NULL;
 protected $zmq = NULL;
 public function __construct() {
  $this->pidfile = '/var/run/'.self::pidfile.'.pid';
 }
 private function daemon(){
  if (file_exists($this->pidfile)) {
   echo "The file $this->pidfile exists.\n";
   exit();
  }
  
  $pid = pcntl_fork();
  if ($pid == -1) {
    die('could not fork');
  } else if ($pid) {
    // we are the parent
    //pcntl_wait($status); //Protect against Zombie children
   exit($pid);
  } else {
   // we are the child
   file_put_contents($this->pidfile, getmypid());
   posix_setuid(self::uid);
   posix_setgid(self::gid);
   return(getmypid());
  }
 }
 private function start(){
  $pid = $this->daemon();
  $this->pool = new Pool(self::MAXCONN, \ExampleWorker::class, []);
  $this->zmq = new ZMQSocket(new ZMQContext(), ZMQ::SOCKET_REP);
  $this->zmq->bind(self::LISTEN);
  
  /* Loop receiving and echoing back */
  while ($message = $this->zmq->recv()) {
   //print_r($message);
   //if($trades){
     $this->pool->submit(new Fee($message));
     $this->zmq->send('TRUE'); 
   //}else{
   // $this->zmq->send('FALSE'); 
   //}
  }
  $pool->shutdown(); 
 }
 private function stop(){

  if (file_exists($this->pidfile)) {
   $pid = file_get_contents($this->pidfile);
   posix_kill($pid, 9); 
   unlink($this->pidfile);
  }
 }
 private function help($proc){
  printf("%s start | stop | help \n", $proc);
 }
 public function main($argv){
  if(count($argv) < 2){
   printf("please input help parameter\n");
   exit();
  }
  if($argv[1] === 'stop'){
   $this->stop();
  }else if($argv[1] === 'start'){
   $this->start();
  }else{
   $this->help($argv[0]);
  }
 }
}

$cgse = new Example();
$cgse->main($argv);

5.1. 프로그램 시작

다음은 프로그램 시작 후 백그라운드로 진입하는 코드입니다

프로세스 ID 파일을 통해 현재 프로세스 상태를 판단합니다. 프로세스 ID 파일이 존재하는 경우 이는 file_exists($this->pidfile) 코드를 통해 수행된다는 의미입니다. 종료되면 파일을 실행하기 전에 수동으로 삭제해야 합니다.

private function daemon(){
  if (file_exists($this->pidfile)) {
   echo "The file $this->pidfile exists.\n";
   exit();
  }
  
  $pid = pcntl_fork();
  if ($pid == -1) {
    die('could not fork');
  } else if ($pid) {
   // we are the parent
   //pcntl_wait($status); //Protect against Zombie children
   exit($pid);
  } else {
   // we are the child
   file_put_contents($this->pidfile, getmypid());
   posix_setuid(self::uid);
   posix_setgid(self::gid);
   return(getmypid());
  }
 }

프로그램이 시작된 후 상위 프로세스가 시작되고 하위 프로세스가 백그라운드에서 실행되며 하위 프로세스 권한이 루트에서 지정된 사용자로 전환되고 pid가 프로세스 ID 파일에 기록됩니다.

5.2. 프로그램 중단

프로그램이 중지되고 pid 파일을 읽은 다음 posix_kill($pid, 9)을 호출하고 마지막으로 파일을 삭제합니다.

private function stop(){

  if (file_exists($this->pidfile)) {
   $pid = file_get_contents($this->pidfile);
   posix_kill($pid, 9); 
   unlink($this->pidfile);
  }
 }

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.