PHP Framework
Laravel
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]
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__,'workerHandleSignal'],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__,'handleMasterSignal'],false);
pcntl_signal(SIGTERM,[__CLASS__,'handleMasterSignal'],false);
pcntl_signal(SIGUSR1,[__CLASS__,'handleMasterSignal'],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 'vendor/autoload.php';
$process = new \Chen\Worker\Server();
$process->workerJob = [new \Chen\Worker\Talk(),new \Chen\Worker\Job()];
$process->run();![1570008925418058.png PHP multi-process and signal interrupt realize multi-task resident memory management [Master/Worker model]](https://img.php.cn/upload/image/452/401/937/1570008925418058.png?x-oss-process=image/resize,p_40)
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!
Laravel in Action: Real-World Applications and ExamplesApr 16, 2025 am 12:02 AMLaravelcanbeeffectivelyusedinreal-worldapplicationsforbuildingscalablewebsolutions.1)ItsimplifiesCRUDoperationsinRESTfulAPIsusingEloquentORM.2)Laravel'secosystem,includingtoolslikeNova,enhancesdevelopment.3)Itaddressesperformancewithcachingsystems,en
Laravel's Primary Function: Backend DevelopmentApr 15, 2025 am 12:14 AMLaravel's core functions in back-end development include routing system, EloquentORM, migration function, cache system and queue system. 1. The routing system simplifies URL mapping and improves code organization and maintenance. 2.EloquentORM provides object-oriented data operations to improve development efficiency. 3. The migration function manages the database structure through version control to ensure consistency. 4. The cache system reduces database queries and improves response speed. 5. The queue system effectively processes large-scale data, avoid blocking user requests, and improve overall performance.
Laravel's Backend Capabilities: Databases, Logic, and MoreApr 14, 2025 am 12:04 AMLaravel performs strongly in back-end development, simplifying database operations through EloquentORM, controllers and service classes handle business logic, and providing queues, events and other functions. 1) EloquentORM maps database tables through the model to simplify query. 2) Business logic is processed in controllers and service classes to improve modularity and maintainability. 3) Other functions such as queue systems help to handle complex needs.
Laravel's Versatility: From Simple Sites to Complex SystemsApr 13, 2025 am 12:13 AMThe Laravel development project was chosen because of its flexibility and power to suit the needs of different sizes and complexities. Laravel provides routing system, EloquentORM, Artisan command line and other functions, supporting the development of from simple blogs to complex enterprise-level systems.
Laravel (PHP) vs. Python: Development Environments and EcosystemsApr 12, 2025 am 12:10 AMThe comparison between Laravel and Python in the development environment and ecosystem is as follows: 1. The development environment of Laravel is simple, only PHP and Composer are required. It provides a rich range of extension packages such as LaravelForge, but the extension package maintenance may not be timely. 2. The development environment of Python is also simple, only Python and pip are required. The ecosystem is huge and covers multiple fields, but version and dependency management may be complex.
Laravel and the Backend: Powering Web Application LogicApr 11, 2025 am 11:29 AMHow does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.
Why is Laravel so popular?Apr 02, 2025 pm 02:16 PMLaravel's popularity includes its simplified development process, providing a pleasant development environment, and rich features. 1) It absorbs the design philosophy of RubyonRails, combining the flexibility of PHP. 2) Provide tools such as EloquentORM, Blade template engine, etc. to improve development efficiency. 3) Its MVC architecture and dependency injection mechanism make the code more modular and testable. 4) Provides powerful debugging tools and performance optimization methods such as caching systems and best practices.
Which is better, Django or Laravel?Mar 28, 2025 am 10:41 AMBoth Django and Laravel are full-stack frameworks. Django is suitable for Python developers and complex business logic, while Laravel is suitable for PHP developers and elegant syntax. 1.Django is based on Python and follows the "battery-complete" philosophy, suitable for rapid development and high concurrency. 2.Laravel is based on PHP, emphasizing the developer experience, and is suitable for small to medium-sized projects.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.





