PHP Kernel Understanding: Life cycle and run mode _php tutorial

Source: Internet
Author: User
Tags sapi server memory

PHP Kernel Understanding: Life cycle and operating mode


PHP run mode

1) CGI (Universal Gateway Interface/Common Gateway Interface)
2) FastCGI (resident type cgi/long-live CGI)
3) CLI (command line run/Interface)
4) Web module mode (the mode of operation of Web server such as Apache)
5) ISAPI (Internet Server application program Interface)
Note: After PHP5.3, PHP no longer has ISAPI mode

CGI is a protocol, it doesn't matter what the process is. What is that fastcgi? FastCGI is used to improve the performance of CGI programs.

CGI implementations in PHP

The CGI implementation of PHP is essentially a server that implements a TCP or UDP protocol in socket programming, and when started, creates a socket listener for the TCP/UDP protocol server and receives the relevant request for processing. This is just the processing of the request, which is based on the addition of module initialization, SAPI initialization, module shutdown, SAPI shutdown, etc., which constitute the entire CGI life cycle.

Cgi

The CGI full name is the Universal Gateway Interface (Common Gateway Interface), which allows a client to request data from a Web browser to a program that executes on a Web server.

CGI describes a standard for transferring data between the client and the program.
One purpose 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 a relatively old pattern, and it has seldom been used in recent years.

For each user request, the child process of the CGI is created first, then the request is processed, and the child process is finished after processing, which is the Fork-and-execute mode. When the user requests a very long time, will be heavily crowding out the system resources such as memory, CPU times, resulting in low performance. So how many CGI sub-processes are there for the CGI server, and the sub-process loading is the main reason for the poor CGI performance.

When the Web server receives the/index.php request, it launches the corresponding CGI program, which is the parser for PHP. The PHP parser then parses the php.ini file, initializes the execution environment, then processes the request, and then returns the processed result in a format specified by the CGI, exiting the process. The Web server then returns the results to the browser.

FastCGI

FAST-CGI is an upgraded version of CGI, FastCGI like a resident (long-live) type of CGI, it can be executed all the time, as long as the activation, not each time to spend a fork once (this is the most criticized by CGI Fork-and-execute mode )。

FastCGI Working principle

When Web server starts, load the FastCGI process Manager "PHP FastCGI process Manager is PHP-FPM (php-fastcgi processes manager)" (IIS ISAPI or Apache Module) The FASTCGI process Manager itself initializes, initiates multiple CGI interpreter processes (visible multiple php-cgi.exe or PHP-CIG) and waits for a connection from the Web server, and when a client request arrives at the Web server, The FASTCGI process Manager selects and connects to a CGI interpreter. Web server sends the CGI environment variables and standard input to the FASTCGI child process php-cgi The FASTCGI child process finishes processing to return the standard output and error information from the same connection to the Web server. When the fastcgi child process closes the connection, the request is processed to completion. The fastcgi child process then waits and processes the next connection from the FASTCGI process Manager (running in webserver). In the normal CGI mode, php-cgi.exe exits here. In CGI mode, you can imagine how slow CGI is usually. Every Web request PHP must re-parse php.ini, reload all DLL extensions, and initialize all data structures. With fastcgi, all of this occurs only once when the process is started. An additional benefit is that the persistent database connection (persistent connection) can work.

Note: PHP's FastCGI process Manager is PHP-FPM (php-fastcgi processes manager)

Advantages

From a stability perspective, fastcgi runs CGI with a separate process pool, a single process dies, the system can easily discard, and then reassign new processes to run the logic, and from a security perspective, FASTCGI supports distributed operations. FastCGI and the host server is completely independent, fastcgi how down will not bring the server down; From a performance perspective, fastcgi separates the processing of dynamic logic from the server, and the heavy-duty IO processing is left to the host server. In this way, the host server can be a single-minded Io, for a normal Dynamic Web page, the logical processing may be only a small number of images, such as static.

Insufficient

Because it is multi-process, so consumes more server memory than CGI multithreading, php-cgi interpreter consumes 7 to 25 megabytes per process, multiplying this number by 50 or 100 is a large amount of memory.

Nginx 0.8.46+php 5.2.14 (FastCGI) server in 30,000 concurrent connection, open 10 Nginx process consumes 150M memory (15m*10=150m), open 64 php-cgi process consumes 1280M of memory (20m*64= 1280M), combined with the memory consumed by the system itself, consumes less than 2GB of memory. If the server memory is small, you can only open 25 php-cgi processes, so that the total amount of memory consumed by php-cgi is 500M.

The above data is from the Nginx 0.8.x + PHP 5.2.13 (FastCGI) build 10 times times more than Apache Web Server (6th edition)

Cli

PHP-CLI is the short name of PHP command line interface, which is the interface that PHP runs on the command lines, different from the PHP environment (PHP-CGI,ISAPI, etc.) running on the Web server.
In other words, PHP can not only write the foreground page, it can also be used to write the background of the program. PHP's CLI shell scripts apply to all PHP advantages, making it either support scripts or systems or even with GUI applications that support PHP-CLI mode under Windows and Linux.

We often use "php–m" under Linux to find PHP installed those extensions is the PHP command line running mode;

PHP Start and end stages

PHP begins execution after two main stages: the start phase before processing the request and the end phase after the request.

Start stage

Module initialization Phase Minit

The process takes place only once throughout the SAPI life cycle, such as during the entire life cycle of Apache startup or throughout the execution of a command-line program.

After starting Apache, the PHP interpreter also starts;
PHP calls the Minit method of each extension (module), which enables these extensions to switch to the available state.

PHP_MINIT_FUNCTION(myphpextension){    // 注册常量或者类等初始化操作    return SUCCESS; }

Module Activation Phase Rinit

This process occurs during the request phase, such as requesting a page through a URL, which is module-activated before each request (the Rinit request begins).
After the request arrives, the SAPI layer gives control to the PHP layer, and PHP initializes the environment variables required for this request to execute the script

For example, the Rinit of the session module, if the session module is enabled in PHP.ini, the $_session variable is initialized when the module's rinit is called, and the relevant content is read, and then PHP invokes all module rinit functions, called "Request initialization." ”。
At this stage the modules can also perform some related operations, the module's Rinit function and the Minit function are similar, the Rinit method can be regarded as a preparatory process, and will start automatically before the program executes.

End Stage

After the request has been processed, it enters the end stage, and the general script executes to the end or by calling the exit () or the Die () function, PHP will go to the end stage. Corresponding to the start phase, the end stage is divided into two links, one at the end of the request (Rshuwdown), and one at the end of the SAPI life cycle (Mshutdown).

After the request is over (Rshuwdown)

Once the request has been processed, the end stage is reached and PHP starts the cleanup program.
It invokes the Rshutdown method of each module sequentially.
Rshutdown is used to clear the symbol table generated by the program runtime, which is called the unset function for each variable.

SAPI at the end of the life cycle (Mshutdown)

Finally, all requests have been processed.
SAPI's ready to shut down.
PHP calls each extension's Mshutdown method
This is the last opportunity for each module to release memory.
(This is for SAPI such as CGI and CLI, there is no "next request", so SAPI immediately begins to shut down. )

The entire PHP life cycle is over. It is important to note that the "Start first step" and "close second step" are performed only if the server does not have a request.

SAPI several stages of running PHP

Module initialization phase (Modules init)

    即调用每个拓展源码中的的PHP_MINIT_FUNCTION中的方法初始化模块,进行一些模块所需变量的申请,内存分配等。

Request initialization phase (ask Init)

 即接受到客户端的请求后调用每个拓展的PHP_RINIT_FUNCTION中的方法,初始化PHP脚本的执行环境。
Execute PHP Script

Request End (ask Shutdown)

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

Close module (modules shutdown)

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

Single-Process SAPI life cycle

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

Multi-process SAPI life cycle

PHP is usually compiled as a module of Apache to handle PHP requests. Apache will generally adopt a multi-process mode, Apache will fork out many sub-processes, each process of memory space independent, each child process will go through the start and end of each process start phase only after the process has been fork out, Multiple requests may be processed throughout the lifetime of the process. The shutdown phase occurs only when Apache is closed or the process is ended, and between these two phases begins with each request repeating the request-the link of the request shutdown.

Multi-threaded SAPI life cycle

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

In this mode, only one server process is running, but it will run many threads at the same time, which can reduce some resource overhead, just need to run it once for Module Init and module shutdown, and some global variables only need to be initialized once, because the thread has unique characteristics, Makes it possible to share some data conveniently between requests.


http://www.bkjia.com/PHPjc/1113010.html www.bkjia.com true http://www.bkjia.com/PHPjc/1113010.html techarticle PHP Kernel Understanding: Life cycle and operating mode PHP operating mode 1) CGI (Universal Gateway Interface/Common Gateway Interface) 2) FastCGI (resident cgi/long-live CGI) 3) CLI (Command ...

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.