Home > Backend Development > PHP Tutorial > Understanding PHP Kernel: Life Cycle and Operation Mode_PHP Tutorial

Understanding PHP Kernel: Life Cycle and Operation Mode_PHP Tutorial

WBOY
Release: 2016-07-12 08:56:27
Original
980 people have browsed it

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.

Understanding PHP Kernel: Life Cycle and Operation Mode_PHP Tutorial

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>
Copy after login

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 request

For 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>
Copy after login

Request init

<code> 即接受到客户端的请求后调用每个拓展的PHP_RINIT_FUNCTION中的方法,初始化PHP脚本的执行环境。
</code>
Copy after login
Execute PHP script

Request Shutdown

<code>这时候调用每个拓展的PHP_RSHUTDOWN_FUNCTION方法清理请求现场,并且ZE开始回收变量和内存
</code>
Copy after login

Module shutdown

<code>Web服务器退出或者命令行脚本执行完毕退出会调用拓展源码中的PHP_MSHUTDOWN_FUNCTION 方法
</code>
Copy after login

Single-process SAPI life cycle

<code>CLI/CGI模式的PHP属于单进程的SAPI模式。这类的请求在处理一次请求后就关闭。
也就是只会经过如下几个环节: 开始 - 请求开始 - 请求关闭 - 结束 SAPI接口实现就完成了其生命周期。
</code>
Copy after login

Understanding PHP Kernel: Life Cycle and Operation Mode_PHP Tutorial

多进程SAPI生命周期

通常PHP是编译为apache的一个模块来处理PHP请求。 Apache一般会采用多进程模式, Apache启动后会fork出多个子进程,每个进程的内存空间独立,每个子进程都会经过开始和结束环节 每个进程的开始阶段只在进程fork出来以来后进行,在整个进程的生命周期内可能会处理多个请求。 只有在Apache关闭或者进程被结束之后才会进行关闭阶段,在这两个阶段之间会随着每个请求重复请求开始-请求关闭的环节。
Understanding PHP Kernel: Life Cycle and Operation Mode_PHP Tutorial

多线程的SAPI生命周期

<code>多线程模式和多进程中的某个进程类似,不同的是在整个进程的生命周期内会并行的重复着 请求开始-请求关闭的环节.
</code>
Copy after login

在这种模式下,只有一个服务器进程在运行着,但会同时运行很多线程,这样可以减少一些资源开销,向Module init和Module shutdown就只需要运行一遍就行了,一些全局变量也只需要初始化一次,因为线程独具的特质,使得各个请求之间方便的共享一些数据成为可能。
Understanding PHP Kernel: Life Cycle and Operation Mode_PHP Tutorial


www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1113010.htmlTechArticlePHP内核了解:生命周期及运行模式 PHP运行模式 1)CGI(通用网关接口 / Common Gateway Interface) 2)FastCGI(常驻型CGI / Long-Live CGI) 3)CLI(命令...
Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template