


Understanding PHP Kernel: Life Cycle and Operation Mode_PHP Tutorial
Understanding PHP kernel: life cycle and operation mode
PHP running mode
1) CGI (Common Gateway Interface)
2) FastCGI (Resident CGI / Long-Live CGI)
3) CLI (Command Line Interface)
4) Web module mode (the mode in which web servers such as Apache run)
5) ISAPI (Internet Server Application Program Interface)
Note: After PHP5.3, PHP no longer has ISAPI mode
CGI is a protocol and has nothing to do with processes or anything like that. So what is fastcgi? Fastcgi is used to improve the performance of CGI programs.
CGI implementation in PHP
The essence of PHP's CGI implementation is to implement a TCP or UDP protocol server through socket programming. When it is started, it creates a socket monitor for the TCP/UDP protocol server and receives related requests for processing. This is just the processing of the request. On this basis, adding module initialization, sapi initialization, module closing, sapi closing, etc. constitutes the entire CGI life cycle.
CGI
The full name of CGI is "Common Gateway Interface", which allows a client to request data from a web browser to a program executing on a web server.
CGI describes a standard for transferring data between the client and this program.
One of the purposes of CGI is to be independent of any language, so CGI can be written in any language as long as the language has standard input, output and environment variables. Such as php, perl, tcl, etc.
CGI is already an older model and has rarely been used in recent years.
Every time there is a user request, a CGI sub-process will be created first, then the request will be processed, and the sub-process will be terminated after processing. This is the Fork-And-Execute mode. When the number of user requests is very large, a large amount of system resources such as memory, CPU time, etc. will be occupied, resulting in low performance. Therefore, a server using CGI will have as many CGI sub-processes as there are connection requests. Repeated loading of sub-processes is the main reason for low CGI performance.When the web server receives the request for /index.php, it will start the corresponding CGI program, which is the PHP parser. Next, the PHP parser will parse the php.ini file, initialize the execution environment, process the request, return the processed result in the format specified by CGI, and exit the process. The web server then returns the results to the browser.
FastCGI
fast-cgi is an upgraded version of cgi. FastCGI is like a long-live CGI. It can be executed all the time. As long as it is activated, it will not take time to fork every time (this It is the most criticized fork-and-execute mode of CGI).
How FastCGI works
The FastCGI process manager is loaded when the Web Server starts [PHP's FastCGI process manager is PHP-FPM (php-FastCGI Process Manager)] (IIS ISAPI or Apache Module). The FastCGI process manager initializes itself and starts multiple CGI interpreter processes. (Multiple php-cgi.exe or php-cig are visible) and wait for the connection from the Web Server; when the client request reaches the Web Server, the FastCGI process manager selects and connects to a CGI interpreter. The Web server sends the CGI environment variables and standard input to the FastCGI subprocess php-cgi. After the FastCGI subprocess completes processing, it returns the standard output and error information to the Web Server from the same connection. When the FastCGI child process closes the connection, the request is processed. The FastCGI child process then waits for and handles the next connection from the FastCGI process manager (running in WebServer). In normal CGI mode, php-cgi.exe exits here. In CGI mode, you can imagine how slow CGI usually is. Every web request to PHP must re-parse php.ini, reload all dll extensions and re-initialize all data structures. With FastCGI, all of this happens only once, when the process starts. An added bonus is that persistent database connections work.Note: PHP’s FastCGI Process Manager is PHP-FPM (PHP-FastCGI Process Manager)
Advantages
From a stability point of view, FastCGI uses an independent process pool to run CGI. If a single process dies, the system can easily discard it and then reallocate a new process to run the logic; from a security point of view, FastCGI supports distributed Operation. FastCGI is completely independent from the host server. No matter how FastCGI goes down, it will not bring down the server. From a performance point of view, FastCGI separates the processing of dynamic logic from the server, and the heavy-load IO processing is still left to the host server. In this way, the host server You can do IO wholeheartedly. For an ordinary dynamic web page, there may only be a small part of the logical processing, and a large number of static images and so on.Insufficient
Because it is multi-process, it consumes more server memory than CGI multi-threading. The PHP-CGI interpreter consumes 7 to 25 megabytes of memory per process. Multiply this number by 50 or 100 to get a large amount of memory.
Nginx 0.8.46 PHP 5.2.14 (FastCGI) server has 30,000 concurrent connections. The 10 Nginx processes started consume 150M memory (15M*10=150M), and the 64 php-cgi processes started consume 1280M memory. (20M*64=1280M), plus the memory consumed by the system itself, the total memory consumption is less than 2GB. If the server memory is small, you can only open 25 php-cgi processes, so that the total memory consumed by php-cgi is only 500M.
The above data is excerpted from Nginx 0.8.x PHP 5.2.13 (FastCGI) to build a web server that is ten times better than Apache (version 6)
CLI
PHP-CLI is the abbreviation of PHP Command Line Interface, which is the interface for PHP to run on the command line, which is different from the PHP environment (PHP-CGI, ISAPI, etc.) running on the web server.
In other words, PHP can not only write front-end web pages, it can also be used to write back-end programs. PHP CLI Shell Scripting applies to all PHP advantages, enabling the creation of either scripts or server-side systems or even with GUI applications. PHP-CLI mode is supported under both Windows and Linux.We often use "php -m" under Linux to find out which extensions PHP has installed, which is the PHP command line running mode;
PHP start and end phases
After PHP starts executing, it will go through two main stages: the starting stage before processing the request and the ending stage after the request.
Starting phase
Module initialization phase MINIT
This process is only performed once during the entire SAPI life cycle (such as the entire life cycle after Apache is started or the entire execution process of the command line program).
After starting Apache, the PHP interpreter will also start;
PHP calls the MINIT method of each extension (module), thereby switching these extensions to an available state.
<code class="language-c hljs ">PHP_MINIT_FUNCTION(myphpextension) { // 注册常量或者类等初始化操作 return SUCCESS; }</code>
Module activation phase RINIT
This process occurs in the request phase. For example, if a page is requested through a URL, module activation will be performed before each request (RINIT request starts).
After the request arrives, the SAPI layer hands over control to the PHP layer, and PHP initializes the environment variables required to execute the script for this requestFor example, it is the RINIT of the Session module. If the Session module is enabled in php.ini, then when calling the RINIT of the module, the $_SESSION variable will be initialized and the relevant content will be read in; then PHP will call RINIT of all modules Function, namely "request initialization".
At this stage, each module can also perform some related operations. The RINIT function of the module is similar to the MINIT function. The RINIT method can be regarded as a preparation process, which will automatically start before the program is executed.
End stage
After the request is processed, it enters the end phase. Generally, when the script is executed to the end or by calling the exit() or die() function, PHP will enter the end phase. Corresponding to the start phase, the end phase is also divided into two stages. , one after the request ends (RSHUWDOWN), and one after the SAPI life cycle ends (MSHUTDOWN).
After the request ends (RSHUWDOWN)
After the request is processed, it enters the end stage, and PHP will start the cleanup process.
It will call the RSHUTDOWN method of each module in sequence.
RSHUTDOWN is used to clear the symbol table generated when the program is running, that is, to call the unset function on each variable.
At the end of the SAPI life cycle (MSHUTDOWN)
Finally, all requests have been processed
SAPI is also preparing to close
PHP calls the MSHUTDOWN method of each extension
This is the last chance for each module to release memory.
(This is for SAPI such as CGI and CLI, there is no "next request", so the SAPI starts to close immediately.)
The entire PHP life cycle is over. It should be noted that the "starting step one" and "closing step two" will only be executed if there is no request from the server.
Several stages that SAPI goes through when running PHP
Module initialization phase (Module init)
<code> 即调用每个拓展源码中的的PHP_MINIT_FUNCTION中的方法初始化模块,进行一些模块所需变量的申请,内存分配等。 </code>
Request init
<code> 即接受到客户端的请求后调用每个拓展的PHP_RINIT_FUNCTION中的方法,初始化PHP脚本的执行环境。 </code>
Request Shutdown
<code>这时候调用每个拓展的PHP_RSHUTDOWN_FUNCTION方法清理请求现场,并且ZE开始回收变量和内存 </code>
Module shutdown
<code>Web服务器退出或者命令行脚本执行完毕退出会调用拓展源码中的PHP_MSHUTDOWN_FUNCTION 方法 </code>
Single-process SAPI life cycle
<code>CLI/CGI模式的PHP属于单进程的SAPI模式。这类的请求在处理一次请求后就关闭。 也就是只会经过如下几个环节: 开始 - 请求开始 - 请求关闭 - 结束 SAPI接口实现就完成了其生命周期。 </code>
多进程SAPI生命周期
通常PHP是编译为apache的一个模块来处理PHP请求。 Apache一般会采用多进程模式, Apache启动后会fork出多个子进程,每个进程的内存空间独立,每个子进程都会经过开始和结束环节 每个进程的开始阶段只在进程fork出来以来后进行,在整个进程的生命周期内可能会处理多个请求。 只有在Apache关闭或者进程被结束之后才会进行关闭阶段,在这两个阶段之间会随着每个请求重复请求开始-请求关闭的环节。
多线程的SAPI生命周期
<code>多线程模式和多进程中的某个进程类似,不同的是在整个进程的生命周期内会并行的重复着 请求开始-请求关闭的环节. </code>
在这种模式下,只有一个服务器进程在运行着,但会同时运行很多线程,这样可以减少一些资源开销,向Module init和Module shutdown就只需要运行一遍就行了,一些全局变量也只需要初始化一次,因为线程独具的特质,使得各个请求之间方便的共享一些数据成为可能。

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

What does WeChat Do Not Disturb mode mean? Nowadays, with the popularity of smartphones and the rapid development of mobile Internet, social media platforms have become an indispensable part of people's daily lives. WeChat is one of the most popular social media platforms in China, and almost everyone has a WeChat account. We can communicate with friends, family, and colleagues in real time through WeChat, share moments in our lives, and understand each other’s current situation. However, in this era, we are also inevitably faced with the problems of information overload and privacy leakage, especially for those who need to focus or

iOS devices have long been able to track your sleep patterns and more using the Health app. But isn’t it annoying when you’re disturbed by notifications while you’re sleeping? These notifications may be irrelevant and therefore disrupt your sleep patterns in the process. While Do Not Disturb mode is a great way to avoid distractions while sleeping, it can cause you to miss important calls and messages you receive during the night. Thankfully, this is where sleep mode comes in. Let’s learn more about it and how to use it on iPhone. What role does sleep mode play on the iPhone? Sleep mode is a dedicated focus mode in iOS that is automatically activated based on your sleep schedule in the "Health" App. It helps you set an alarm and then

To install the Linux kernel on Ubuntu22.04, you can follow the following steps: Update the system: First, make sure your Ubuntu system is the latest, execute the following command to update the system package: sudoaptupdatesudoaptupgrade Download the kernel file: Visit the official Linux kernel website () to download Required kernel version. Select a stable version and download the source code file (with .tar.gz or .tar.xz extension), for example: wget Unzip the file: Use the following command to unzip the downloaded kernel source code file: tar-xflinux-5.14.tar. xz install build dependencies: Install the tools and dependencies required to build the kernel. Execute

Modify the kernel startup sequence of Linux 1. Modify the kernel startup sequence of RHEL6/CentOS6. Check the /etc/grub.conf file to determine the system kernel situation. According to the document, there are two kernel versions in the system, namely 2.6.32-573.18.1.el6.x86_64 and 2.6.32-431.23.3.el6.x86_64. Kernel versions are listed from top to bottom. In the grub.conf file, you can decide which kernel version to use when the system starts by adjusting the default parameters. The default value is 0, which means the system will boot the latest kernel version. A value of 0 corresponds to the first content listed in the grub.conf file.

Even answering calls in Do Not Disturb mode can be a very annoying experience. As the name suggests, Do Not Disturb mode turns off all incoming call notifications and alerts from emails, messages, etc. You can follow these solution sets to fix it. Fix 1 – Enable Focus Mode Enable focus mode on your phone. Step 1 – Swipe down from the top to access Control Center. Step 2 – Next, enable “Focus Mode” on your phone. Focus Mode enables Do Not Disturb mode on your phone. It won't cause any incoming call alerts to appear on your phone. Fix 2 – Change Focus Mode Settings If there are some issues in the focus mode settings, you should fix them. Step 1 – Open your iPhone settings window. Step 2 – Next, turn on the Focus mode settings

The epc+o model refers to the general contracting framework that integrates design, procurement, etc. It is some operational links derived from epc; that is, during the construction period, the general contractor must not only undertake design tasks in the traditional sense In addition, it also has to undertake all maintenance tasks during the operation period. This model can greatly improve the operational efficiency of many projects and quickly reduce operating costs.

Windows in S mode is designed to provide enhanced security and performance by only allowing the installation of apps from the Microsoft Store. While this feature helps prevent malware and ensure a secure computing environment, it may limit users who want to install applications from sources other than the Microsoft Store. If you find yourself in this situation and keep asking yourself how to switch out of S mode in Windows 10/11, then you have come to the right place as we will walk you through how to switch out in Windows 10/11 using two different methods Steps to S Mode ensure you can enjoy the freedom of installing apps from anywhere you choose. Learn how to switch out of S mode in Windows

On iPhone 15 Pro and iPhone 15 Pro Max models, Apple introduced a physically programmable action button that replaces the traditional ring/silent switch above the volume buttons. The action button can be programmed to perform several different functions, but the ability to switch between silent and ring modes isn't gone. By default, a long press on the action button will silence the device and the button's tactile feedback will pulse three times. Both iPhone 15 Pro models will display a crossed-out bell symbol next to the time in the status bar to indicate that silent/silent mode is activated, and it will remain so until you long-press the Action button again to unmute the device. If you prefer to put your iPhone in silent mode
