Home  >  Article  >  PHP Framework  >  PHP multi-process and signal interrupt realize multi-task resident memory management [Master/Worker model]

PHP multi-process and signal interrupt realize multi-task resident memory management [Master/Worker model]

藏色散人
藏色散人forward
2019-10-02 17:37:442400browse

This article is based on multi-process testing done by pcntl extension.

Process Scheduling Strategy

The operating system is responsible for the scheduling of parent and child processes. The specific scheduling of the child process or the parent process first is determined by the system's scheduling algorithm. Of course, the parent process can be scheduled first. Adding a delay to the process or calling the process recycling function pcntl_wait can let the child process run first. The purpose of process recycling is to release the memory space occupied when the process is created to prevent it from becoming a zombie process.

Signal:

The signal is called the soft interrupt system or soft interrupt. Its function is to send asynchronous event notifications to the process.

Signal number: [The source code is based on SIGINT, SIGTERM, SIGUSR1 signals, please check the kill command manual for the meaning, no description is given]

linux supports 64, half of them are Half of the real-time signals are non-real-time signals. These signals have their own numbers and corresponding integer values. Readers can refer to the relevant Linux manuals for the meaning of each signal number [you can find out by looking at the man manual]

Signal processing function:

Signals are generally bound to the corresponding Functions, some have default actions such as SIGKILL, SIGTERM, SIGINT. The default operation is to kill the process. Of course, we can override it by overriding it through pcntl_signal.

The concept of signal: It is the same as hardware interrupt. Please refer to my previous articles or check the chip hardware interrupt principle.

Signal sending:

kill signal number process or the interrupt signal of the key product or you can use posix_kill and other functions in the source code.

Processes are isolated from each other and have their own stack space. In addition to some common text [code area], they also have their own executable code. When the process is running, it will occupy CPU resources and other processes will not have access to it. Right to run, at this time other processes will be in a blocked state [such as the tcp service mentioned earlier]. When the process ends [run to the last sentence of the code or encounter return or exit, exit the process function or encounter It will exit when a signal event occurs] Give up permissions and release memory, and other processes will have the opportunity to run.

The process has its own process descriptor, of which the process number PID is more commonly used. When the process is running, the corresponding process file will be generated under the system /proc/PID, and the user can view it by himself.

Each process has its own process group [collection of processes]. A collection of multiple process groups is a session. Creating a session is created through a process, and this process cannot be the group leader process. , this process will become the session first process during the session, and will also become the process leader of the process group. At the same time, it will leave the control terminal. Even if the previous process is bound to the control terminal, it will leave [Creation of Daemon Process].

File description permission mask [Permission mask word]:

umask () You can run this command in linux, then create the file and view its permissions [ If you don’t find anything after running, it means you still haven’t trained enough^_^】

<?php
/**
 * Created by PhpStorm.
 * User: 1655664358@qq.com
 * Date: 2018/3/26
 * Time: 14:19
 */
namespace Chen\Worker;
class Server
{
    public $workerPids = [];
    public $workerJob = [];
    public $master_pid_file = "master_pid";
    public $state_file = "state_file.txt";
    function run()
    {
        $this->daemon();
        $this->worker();
        $this->setMasterPid();
        $this->installSignal();
        $this->showState();
        $this->wait();
    }
    function wait()
    {
        while (1){
            pcntl_signal_dispatch();
            $pid = pcntl_wait($status);
            if ($pid>0){
                unset($this->workerPids[$pid]);
            }else{
                if (count($this->workerPids)==0){
                    exit();
                }
            }
            usleep(100000);
        }
    }
    function showState()
    {
        $state = "\nMaster 信息\n";
        $state.=str_pad("master pid",25);
        $state.=str_pad("worker num",25);
        $state.=str_pad("job pid list",10)."\n";
        $state.=str_pad($this->getMasterPid(),25);
        $state.=str_pad(count($this->workerPids),25);
        $state.=str_pad(implode(",",array_keys($this->workerPids)),10);
        echo $state.PHP_EOL;
    }
    function getMasterPid()
    {
        if (file_exists($this->master_pid_file)){
            return file_get_contents($this->master_pid_file);
        }else{
            exit("服务未运行\n");
        }
    }
    function setMasterPid()
    {
        $fp = fopen($this->master_pid_file,"w");
        @fwrite($fp,posix_getpid());
        @fclose($fp);
    }
    function daemon()
    {
        $pid = pcntl_fork();
        if ($pid<0){
            exit("fork进程失败\n");
        }else if ($pid >0){
            exit(0);
        }else{
            umask(0);
            $sid = posix_setsid();
            if ($sid<0){
                exit("创建会话失败\n");
            }
            $pid = pcntl_fork();
            if ($pid<0){
                exit("进程创建失败\n");
            }else if ($pid >0){
                exit(0);
            }
            //可以关闭标准输入输出错误文件描述符【守护进程不需要】
        }
    }
    function worker()
    {
        if (count($this->workerJob)==0)exit("没有工作任务\n");
        foreach($this->workerJob as $job){
            $pid = pcntl_fork();
            if ($pid<0){
                exit("工作进程创建失败\n");
            }else if ($pid==0){
                /***************子进程工作范围**********************/
                //给子进程安装信号处理程序
                $this->workerInstallSignal();
                $start_time = time();
                while (1){
                    pcntl_signal_dispatch();
                    if ((time()-$start_time)>=$job->job_run_time){
                        break;
                    }
                    $job->run(posix_getpid());
                }
                exit(0);//子进程运行完成后退出
                /***************子进程工作范围**********************/
            }else{
                $this->workerPids[$pid] = $job;
            }
        }
    }
    function workerInstallSignal()
    {
        pcntl_signal(SIGUSR1,[__CLASS__,&#39;workerHandleSignal&#39;],false);
    }
    function workerHandleSignal($signal)
    {
        switch ($signal){
            case SIGUSR1:
                $state = "worker pid=".posix_getpid()."接受了父进程发来的自定义信号\n";
                file_put_contents($this->state_file,$state,FILE_APPEND);
                break;
        }
    }
    function installSignal()
    {
        pcntl_signal(SIGINT,[__CLASS__,&#39;handleMasterSignal&#39;],false);
        pcntl_signal(SIGTERM,[__CLASS__,&#39;handleMasterSignal&#39;],false);
        pcntl_signal(SIGUSR1,[__CLASS__,&#39;handleMasterSignal&#39;],false);
    }
    function handleMasterSignal($signal)
    {
        switch ($signal){
            case SIGINT:
                //主进程接受到中断信号ctrl+c
                foreach ($this->workerPids as $pid=>$worker){
                    posix_kill($pid,SIGINT);//向所有的子进程发出
                }
                exit("服务平滑停止\n");
                break;
            case SIGTERM://ctrl+z
                foreach ($this->workerPids as $pid=>$worker){
                    posix_kill($pid,SIGKILL);//向所有的子进程发出
                }
                exit("服务停止\n");
                break;
            case SIGUSR1://用户自定义信号
                if (file_exists($this->state_file)){
                    unlink($this->state_file);
                }
                foreach ($this->workerPids as $pid=>$worker){
                    posix_kill($pid,SIGUSR1);
                }
                $state = "master pid\n".$this->getMasterPid()."\n";
                while(!file_exists($this->state_file)){
                    sleep(1);
                }
                $state.= file_get_contents($this->state_file);
                echo $state.PHP_EOL;
                break;
        }
    }
}  
<?php
/**\
 * Created by PhpStorm.\ * User: 1655664358@qq.com
 * Date: 2018/3/26\ * Time: 14:37\ */\namespace Chen\Worker;
class Job
{
  public $job_run_time = 3600;
  function run($pid)
 {\sleep(3);
  echo "worker pid = $pid job 没事干,就在这里job\n";
  }
}  
<?php
/**
 * Created by PhpStorm.\ * User: 1655664358@qq.com
 * Date: 2018/3/26\ * Time: 14:37\ */\namespace Chen\Worker;
class Talk
{
  public $job_run_time = 3600;
  function run($pid)
 {\sleep(3);
  echo "worker pid = $pid job 没事干,就在这里talk\n";
  }
}
<?php
/**
 * Created by PhpStorm.\ * User: 1655664358@qq.com
 * Date: 2018/3/26\ * Time: 15:45\ */
require_once &#39;vendor/autoload.php&#39;;
$process = new \Chen\Worker\Server();
$process->workerJob = [new \Chen\Worker\Talk(),new \Chen\Worker\Job()];
$process->run();

PHP multi-process and signal interrupt realize multi-task resident memory management [Master/Worker model]

For more Laravel related technical articles, please visit Laravel Framework Getting Started Tutorial column for learning!

The above is the detailed content of PHP multi-process and signal interrupt realize multi-task resident memory management [Master/Worker model]. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete