首頁  >  文章  >  php框架  >  PHP 多進程與訊號中斷實作多任務常駐記憶體管理【Master/Worker 模型】

PHP 多進程與訊號中斷實作多任務常駐記憶體管理【Master/Worker 模型】

藏色散人
藏色散人轉載
2019-10-02 17:37:442407瀏覽

本文章是基於 pcntl 擴充做的多進程測試。

進程調度策略

父子進程的調度由作業系統來負責,具體先調度子進程還是父進程由系統的調度演算法決定,當然可以在父進程加上延時或是呼叫進程回收函數pcntl_wait 可以先讓子程序先運行,進程回收的目的是釋放進程創建時佔用的記憶體空間,防止變成殭屍進程。

訊號:

訊號稱為軟中斷系統或是叫軟中斷,功能是向行程發送非同步事件通知。

訊號編號: 【原始碼基於SIGINT,SIGTERM,SIGUSR1 訊號,意義請自行查看kill 指令手冊,不在描述】

linux 支援64 個,有一半為即時訊號,一半為非時實訊號,這些訊號都有自己的編號和對應的整數值。每個訊號的編號意義讀者可以參考linux 相關手冊【man 手冊看看就知道了】

訊號處理函數:

訊號一般會綁定對應的功能,有的是預設動作如SIGKILL,SIGTERM,SIGINT 操作預設操作就是乾掉進程,當然我們可以重寫覆蓋掉,就是透過pcntl_signal 來覆寫掉。

訊號的概念:與硬體中斷一個道理,請讀者自行參考本人前面擼過的文章或是查看晶片硬體中斷原理。

訊號的發送:

kill 訊號編號 進程 或是按鍵產品的中斷訊號或是在原始碼裡可以使用 posix_kill 等函數。

進程是相互隔離的,擁有自己的堆疊空間,除了一些公用的正文【程式碼區】,同時也有自己的可執行程式碼,進程運行時,將佔用cpu 的資源,其它進程將無權運行,此時其它進程將為阻塞狀態【比如前面擼過的tcp 服務】,當進程運行結束後【運行到代碼的最後一句或是遇到return 或是遇到exit 退出進程函數或是遇到訊號事件時將會退出】讓出權限並釋放掉內存,其它進程就有機會運行了。

進程擁有的自己進程描述符,其中比較常用的是進程號 PID,進程運行時會在系統 /proc/PID 下產生相應的進程文件,用戶可以自行查看。

每個進程都擁有所屬的進程組【進程的集合】,多個進程組集合則是一個會話,創建一個會話是透過一個進程進行創建的,並且此進程不可以為組長進程,此進程將成為會話期的會話首進程,也會成為進程組的進程組長,同時將會脫離控制終端,即使先前的進程綁定了控制終端也會脫離【守護程序的創建】。

文件描述權限遮罩【權限屏蔽字】:

umask () 你可以在linux 執行這個指令,然後建立文件,並查看它的權限【如果你跑完啥也沒發現,說明你還是訓練不夠^_^】

<?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 多進程與訊號中斷實作多任務常駐記憶體管理【Master/Worker 模型】

#更多Laravel相關技術文章,請訪問Laravel框架入門教程欄位進行學習!

以上是PHP 多進程與訊號中斷實作多任務常駐記憶體管理【Master/Worker 模型】的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:learnku.com。如有侵權,請聯絡admin@php.cn刪除