国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
How to write php daemon? Daemon
Articles you may be interested in:
Home Backend Development PHP Tutorial How to write a php daemon (Daemon), daemon_PHP tutorial

How to write a php daemon (Daemon), daemon_PHP tutorial

Jul 12, 2016 am 09:02 AM
php daemon

How to write php daemon? Daemon

Daemon is a special process running in the background. It is independent of the control terminal and periodically performs some task or waits for some event to occur. Daemon is a very useful process. PHP can also implement the function of daemon process.
1. Basic concepts
Process: Each process has a parent process. When the child process exits, the parent process can get the exit status of the child process.
Process Group: Each process belongs to a process group, and each process group has a process group number, which is equal to The PID of the process group leader
2. Key points of daemon programming
1. Run in the background ?
To avoid hanging the control terminal, put Daemon into the background for execution. The method is to call fork in the process to terminate the parent process and let Daemon execute in the background in the child process. if($pid=pcntl_fork()) exit(0);//It is the parent process, end the parent process, and the child process continues
2. Get rid of the controlling terminal and log in to the session and process group
It is necessary to first introduce the relationship between processes and control terminals, login sessions and process groups in Linux: a process belongs to a process group, and the process group number (GID) is the process number (PID) of the process leader ). A login session can contain multiple process groups. These process groups share a controlling terminal. This control terminal is usually the login terminal where the process was created. Controlling terminals, login sessions, and process groups are usually inherited from the parent process. Our purpose is to get rid of them and not be affected by them. The method is to call setsid() based on point 1 to make the process the session leader: posix_setsid();
? ? ? Description: The setsid() call fails when the process is the session leader. But the first point already ensures that the process is not the session leader. After the setsid() call is successful, the process becomes the new session group leader and new process group leader, and is separated from the original login session and process group. Due to the exclusivity of the session process to the control terminal, the process is detached from the control terminal at the same time.
3. Disable the process from reopening the control terminal
Now, the process has become a terminalless session leader. But it can be re-applied to open a control terminal. You can prevent the process from reopening the control terminal by making the process no longer the session leader: if($pid=pcntl_fork()) exit(0);//End the first child process and the second child process continues (the second child process No longer the conversation leader)
4. Close the open file descriptor
A process inherits open file descriptors from the parent process that created it. If it is not closed, system resources will be wasted, the file system where the process is located will not be able to be unmounted, and unpredictable errors will occur. Close them as follows:
???????????? fclose(STDIN), fclose(STDOUT), fclose(STDERR) closes standard input, output and error display.
5. Change the current working directory
When a process is active, the file system where its working directory is located cannot be unmounted. Generally, you need to change the working directory to the root directory. For core dumps that need to be dumped, the process that writes the running log changes the working directory to a specific directory such as chdir("/")
6. Reset file creation mask
A process inherits the file creation mask from the parent process that created it. It may modify the access bits of files created by the daemon. To prevent this, clear the file creation mask: umask(0);
7. Processing SIGCHLD signal
It is not necessary to handle the SIGCHLD signal. But for some processes, especially server processes, child processes are often generated to handle requests when requests arrive. If the parent process does not wait for the child process to end, the child process will become a zombie process (zombie) and occupy system resources. If the parent process waits for the child process to end, it will increase the burden on the parent process and affect the concurrency performance of the server process. Under Linux, you can simply set the operation of the SIGCHLD signal to SIG_IGN. signal(SIGCHLD,SIG_IGN);
This way, the kernel will not create a zombie process when the child process ends. This is different from BSD4. Under BSD4, you must explicitly wait for the child process to end before releasing the zombie process. For questions about signals, please refer to the Linux signal description list
3. Examples

<&#63;php 
* 后臺(tái)腳本控制類 
*/ 
class DaemonCommand{ 
  
  private $info_dir="/tmp"; 
  private $pid_file=""; 
  private $terminate=false; //是否中斷 
  private $workers_count=0; 
  private $gc_enabled=null; 
  private $workers_max=8; //最多運(yùn)行8個(gè)進(jìn)程 
  
  public function __construct($is_sington=false,$user='nobody',$output="/dev/null"){ 
  
      $this->is_sington=$is_sington; //是否單例運(yùn)行,單例運(yùn)行會(huì)在tmp目錄下建立一個(gè)唯一的PID 
      $this->user=$user;//設(shè)置運(yùn)行的用戶 默認(rèn)情況下nobody 
      $this->output=$output; //設(shè)置輸出的地方 
      $this->checkPcntl(); 
  } 
  //檢查環(huán)境是否支持pcntl支持 
  public function checkPcntl(){ 
    if ( ! function_exists('pcntl_signal_dispatch')) { 
      // PHP < 5.3 uses ticks to handle signals instead of pcntl_signal_dispatch 
      // call sighandler only every 10 ticks 
      declare(ticks = 10); 
    } 
  
    // Make sure PHP has support for pcntl 
    if ( ! function_exists('pcntl_signal')) { 
      $message = 'PHP does not appear to be compiled with the PCNTL extension. This is neccesary for daemonization'; 
      $this->_log($message); 
      throw new Exception($message); 
    } 
    //信號(hào)處理 
    pcntl_signal(SIGTERM, array(__CLASS__, "signalHandler"),false); 
    pcntl_signal(SIGINT, array(__CLASS__, "signalHandler"),false); 
    pcntl_signal(SIGQUIT, array(__CLASS__, "signalHandler"),false); 
  
    // Enable PHP 5.3 garbage collection 
    if (function_exists('gc_enable')) 
    { 
      gc_enable(); 
      $this->gc_enabled = gc_enabled(); 
    } 
  } 
  
  // daemon化程序 
  public function daemonize(){ 
  
    global $stdin, $stdout, $stderr; 
    global $argv; 
  
    set_time_limit(0); 
  
    // 只允許在cli下面運(yùn)行 
    if (php_sapi_name() != "cli"){ 
      die("only run in command line mode\n"); 
    } 
  
    // 只能單例運(yùn)行 
    if ($this->is_sington==true){ 
  
      $this->pid_file = $this->info_dir . "/" .__CLASS__ . "_" . substr(basename($argv[0]), 0, -4) . ".pid"; 
      $this->checkPidfile(); 
    } 
  
    umask(0); //把文件掩碼清0 
  
    if (pcntl_fork() != 0){ //是父進(jìn)程,父進(jìn)程退出 
      exit(); 
    } 
  
    posix_setsid();//設(shè)置新會(huì)話組長,脫離終端 
  
    if (pcntl_fork() != 0){ //是第一子進(jìn)程,結(jié)束第一子進(jìn)程   
      exit(); 
    } 
  
    chdir("/"); //改變工作目錄 
  
    $this->setUser($this->user) or die("cannot change owner"); 
  
    //關(guān)閉打開的文件描述符 
    fclose(STDIN); 
    fclose(STDOUT); 
    fclose(STDERR); 
  
    $stdin = fopen($this->output, 'r'); 
    $stdout = fopen($this->output, 'a'); 
    $stderr = fopen($this->output, 'a'); 
  
    if ($this->is_sington==true){ 
      $this->createPidfile(); 
    } 
  
  } 
  //--檢測(cè)pid是否已經(jīng)存在 
  public function checkPidfile(){ 
  
    if (!file_exists($this->pid_file)){ 
      return true; 
    } 
    $pid = file_get_contents($this->pid_file); 
    $pid = intval($pid); 
    if ($pid > 0 && posix_kill($pid, 0)){ 
      $this->_log("the daemon process is already started"); 
    } 
    else { 
      $this->_log("the daemon proces end abnormally, please check pidfile " . $this->pid_file); 
    } 
    exit(1); 
  
  } 
  //----創(chuàng)建pid 
  public function createPidfile(){ 
  
    if (!is_dir($this->info_dir)){ 
      mkdir($this->info_dir); 
    } 
    $fp = fopen($this->pid_file, 'w') or die("cannot create pid file"); 
    fwrite($fp, posix_getpid()); 
    fclose($fp); 
    $this->_log("create pid file " . $this->pid_file); 
  } 
  
  //設(shè)置運(yùn)行的用戶 
  public function setUser($name){ 
  
    $result = false; 
    if (empty($name)){ 
      return true; 
    } 
    $user = posix_getpwnam($name); 
    if ($user) { 
      $uid = $user['uid']; 
      $gid = $user['gid']; 
      $result = posix_setuid($uid); 
      posix_setgid($gid); 
    } 
    return $result; 
  
  } 
  //信號(hào)處理函數(shù) 
  public function signalHandler($signo){ 
  
    switch($signo){ 
  
      //用戶自定義信號(hào) 
      case SIGUSR1: //busy 
      if ($this->workers_count < $this->workers_max){ 
        $pid = pcntl_fork(); 
        if ($pid > 0){ 
          $this->workers_count ++; 
        } 
      } 
      break; 
      //子進(jìn)程結(jié)束信號(hào) 
      case SIGCHLD: 
        while(($pid=pcntl_waitpid(-1, $status, WNOHANG)) > 0){ 
          $this->workers_count --; 
        } 
      break; 
      //中斷進(jìn)程 
      case SIGTERM: 
      case SIGHUP: 
      case SIGQUIT: 
  
        $this->terminate = true; 
      break; 
      default: 
      return false; 
    } 
  
  } 
  /** 
  *開始開啟進(jìn)程 
  *$count 準(zhǔn)備開啟的進(jìn)程數(shù) 
  */ 
  public function start($count=1){ 
  
    $this->_log("daemon process is running now"); 
    pcntl_signal(SIGCHLD, array(__CLASS__, "signalHandler"),false); // if worker die, minus children num 
    while (true) { 
      if (function_exists('pcntl_signal_dispatch')){ 
  
        pcntl_signal_dispatch(); 
      } 
  
      if ($this->terminate){ 
        break; 
      } 
      $pid=-1; 
      if($this->workers_count<$count){ 
  
        $pid=pcntl_fork(); 
      } 
  
      if($pid>0){ 
  
        $this->workers_count++; 
  
      }elseif($pid==0){ 
  
        // 這個(gè)符號(hào)表示恢復(fù)系統(tǒng)對(duì)信號(hào)的默認(rèn)處理 
        pcntl_signal(SIGTERM, SIG_DFL); 
        pcntl_signal(SIGCHLD, SIG_DFL); 
        if(!empty($this->jobs)){ 
          while($this->jobs['runtime']){ 
            if(empty($this->jobs['argv'])){ 
              call_user_func($this->jobs['function'],$this->jobs['argv']); 
            }else{ 
              call_user_func($this->jobs['function']); 
            } 
            $this->jobs['runtime']--; 
            sleep(2); 
          } 
          exit(); 
  
        } 
        return; 
  
      }else{ 
  
        sleep(2); 
      } 
  
  
    } 
  
    $this->mainQuit(); 
    exit(0); 
  
  } 
  
  //整個(gè)進(jìn)程退出 
  public function mainQuit(){ 
  
    if (file_exists($this->pid_file)){ 
      unlink($this->pid_file); 
      $this->_log("delete pid file " . $this->pid_file); 
    } 
    $this->_log("daemon process exit now"); 
    posix_kill(0, SIGKILL); 
    exit(0); 
  } 
  
  // 添加工作實(shí)例,目前只支持單個(gè)job工作 
  public function setJobs($jobs=array()){ 
  
    if(!isset($jobs['argv'])||empty($jobs['argv'])){ 
  
      $jobs['argv']=""; 
  
    } 
    if(!isset($jobs['runtime'])||empty($jobs['runtime'])){ 
  
      $jobs['runtime']=1; 
  
    } 
  
    if(!isset($jobs['function'])||empty($jobs['function'])){ 
  
      $this->log("你必須添加運(yùn)行的函數(shù)!"); 
    } 
  
    $this->jobs=$jobs; 
  
  } 
  //日志處理 
  private function _log($message){ 
    printf("%s\t%d\t%d\t%s\n", date("c"), posix_getpid(), posix_getppid(), $message); 
  } 
  
} 
  
//調(diào)用方法1 
$daemon=new DaemonCommand(true); 
$daemon->daemonize(); 
$daemon->start(2);//開啟2個(gè)子進(jìn)程工作 
work(); 
  
  
  
  
//調(diào)用方法2 
$daemon=new DaemonCommand(true); 
$daemon->daemonize(); 
$daemon->addJobs(array('function'=>'work','argv'=>'','runtime'=>1000));//function 要運(yùn)行的函數(shù),argv運(yùn)行函數(shù)的參數(shù),runtime運(yùn)行的次數(shù) 
$daemon->start(2);//開啟2個(gè)子進(jìn)程工作 
  
//具體功能的實(shí)現(xiàn) 
function work(){ 
   echo "測(cè)試1"; 
} 
&#63;> 

The above is the relevant introduction to the PHP daemon process. I hope it will be helpful to everyone's learning.

Articles you may be interested in:

  • The PHP daemon plus the linux command nohup realizes that the task is executed once every second
  • Overview of the implementation and optimization of the PHP program-level daemon
  • Detailed explanation of multi-process parallel operation in PHP (can be used as a daemon)
  • Shell script is shared as a daemon example to ensure that PHP scripts do not hang up
  • PHP advanced programming examples : Writing daemon process
  • PHP daemon process instance
  • PHP method of using process as daemon process
  • PHP extension program to implement daemon process
  • Sharing PHP daemon process Class

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1086643.htmlTechArticleHow to write php daemon, daemon daemon is a kind of process that runs in the background Special process. It is independent of the control terminal and performs certain tasks periodically...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1502
276
PHP calls AI intelligent voice assistant PHP voice interaction system construction PHP calls AI intelligent voice assistant PHP voice interaction system construction Jul 25, 2025 pm 08:45 PM

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

How to use PHP to build social sharing functions PHP sharing interface integration practice How to use PHP to build social sharing functions PHP sharing interface integration practice Jul 25, 2025 pm 08:51 PM

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization Jul 25, 2025 pm 08:57 PM

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

PHP creates a blog comment system to monetize PHP comment review and anti-brush strategy PHP creates a blog comment system to monetize PHP comment review and anti-brush strategy Jul 25, 2025 pm 08:27 PM

1. Maximizing the commercial value of the comment system requires combining native advertising precise delivery, user paid value-added services (such as uploading pictures, top-up comments), influence incentive mechanism based on comment quality, and compliance anonymous data insight monetization; 2. The audit strategy should adopt a combination of pre-audit dynamic keyword filtering and user reporting mechanisms, supplemented by comment quality rating to achieve content hierarchical exposure; 3. Anti-brushing requires the construction of multi-layer defense: reCAPTCHAv3 sensorless verification, Honeypot honeypot field recognition robot, IP and timestamp frequency limit prevents watering, and content pattern recognition marks suspicious comments, and continuously iterate to deal with attacks.

How to use PHP to combine AI to generate image. PHP automatically generates art works How to use PHP to combine AI to generate image. PHP automatically generates art works Jul 25, 2025 pm 07:21 PM

PHP does not directly perform AI image processing, but integrates through APIs, because it is good at web development rather than computing-intensive tasks. API integration can achieve professional division of labor, reduce costs, and improve efficiency; 2. Integrating key technologies include using Guzzle or cURL to send HTTP requests, JSON data encoding and decoding, API key security authentication, asynchronous queue processing time-consuming tasks, robust error handling and retry mechanism, image storage and display; 3. Common challenges include API cost out of control, uncontrollable generation results, poor user experience, security risks and difficult data management. The response strategies are setting user quotas and caches, providing propt guidance and multi-picture selection, asynchronous notifications and progress prompts, key environment variable storage and content audit, and cloud storage.

PHP realizes commodity inventory management and monetization PHP inventory synchronization and alarm mechanism PHP realizes commodity inventory management and monetization PHP inventory synchronization and alarm mechanism Jul 25, 2025 pm 08:30 PM

PHP ensures inventory deduction atomicity through database transactions and FORUPDATE row locks to prevent high concurrent overselling; 2. Multi-platform inventory consistency depends on centralized management and event-driven synchronization, combining API/Webhook notifications and message queues to ensure reliable data transmission; 3. The alarm mechanism should set low inventory, zero/negative inventory, unsalable sales, replenishment cycles and abnormal fluctuations strategies in different scenarios, and select DingTalk, SMS or Email Responsible Persons according to the urgency, and the alarm information must be complete and clear to achieve business adaptation and rapid response.

Beyond the LAMP Stack: PHP's Role in Modern Enterprise Architecture Beyond the LAMP Stack: PHP's Role in Modern Enterprise Architecture Jul 27, 2025 am 04:31 AM

PHPisstillrelevantinmodernenterpriseenvironments.1.ModernPHP(7.xand8.x)offersperformancegains,stricttyping,JITcompilation,andmodernsyntax,makingitsuitableforlarge-scaleapplications.2.PHPintegrateseffectivelyinhybridarchitectures,servingasanAPIgateway

How to build a PHP Nginx environment with MacOS to configure the combination of Nginx and PHP services How to build a PHP Nginx environment with MacOS to configure the combination of Nginx and PHP services Jul 25, 2025 pm 08:24 PM

The core role of Homebrew in the construction of Mac environment is to simplify software installation and management. 1. Homebrew automatically handles dependencies and encapsulates complex compilation and installation processes into simple commands; 2. Provides a unified software package ecosystem to ensure the standardization of software installation location and configuration; 3. Integrates service management functions, and can easily start and stop services through brewservices; 4. Convenient software upgrade and maintenance, and improves system security and functionality.

See all articles