How to use PHP to write daemon process_PHP tutorial

WBOY
Release: 2016-07-13 17:47:02
Original
820 people have browsed it

This afternoon I saw a question on segmentfault.com. The title of the question was "How to implement service-oriented PHP", which asked whether PHP can only be called via the web. In fact, many people have misunderstandings about the usage scenarios of PHP. They think that PHP can only be used to write web scripts. In fact, starting from PHP4, the usage scenarios of PHP are no longer limited to processing web requests.

From the perspective of PHP's architecture system, PHP is divided into three levels: sapi, php core and zend engine. PHP core itself has no coupling with the web. PHP communicates with other applications through sapi. For example, mod_php is a sapi implementation written for apache. Similarly, fpm is a sapi implementation based on the fastcgi protocol. These sapis are used in conjunction with the web server. Handles web requests. But there are also many sapis that have nothing to do with the web. For example, cli sapi can directly execute php in the command line environment, and embed sapi can embed php into other languages ​​​​(such as Lua). I do not intend to discuss the topic of PHP's architecture system and SAPI in detail here. I just want to explain that from the perspective of architecture system, PHP has already been designed to support various environments and is not unique to the web.

In addition to the support of the architecture system, PHP's rich extension modules also provide support for PHP to function in different environments. For example, the pcntl module and POSIX module mentioned in this article can realize basic process management, signal processing and other operating system-level functions. function, and the sockets module enables PHP to have socket communication capabilities. Therefore, PHP can be used to write tool scripts similar to those commonly used by shell or perl, or even a daemon process with a server nature.

In order to show how to write a daemon server in PHP, I wrote a simple http server in PHP. This server runs as a daemon process. Of course, in order to focus on how to use PHP to write daemons, I did not implement specific business logic for this http server, but it can listen to the specified port, accept http requests and return a fixed text to the client. The whole process is implemented through sockets. All written in php.

Code example

Here is the complete code for this program:

//Accpet the http client request and generate response content.

//As a demo, this function just send "PHP HTTP Server" to client.

function handle_http_request($address, $port)

{

$max_backlog = 16;

$res_content = "HTTP/1.1 200 OK

Content-Length: 15

Content-Type: text/plain; charset=UTF-8

PHP HTTP Server";

$res_len = strlen($res_content);

//Create, bind and listen to socket

If(($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === FALSE)

{

echo "Create socket failed!n";

exit;

}  

If((socket_bind($socket, $address, $port)) === FALSE)

{

echo "Bind socket failed!n";

exit;

}

If((socket_listen($socket, $max_backlog)) === FALSE)

{

echo "Listen to socket failed!n";

exit;

}

//Loop

While(TRUE)

{

If(($accept_socket = socket_accept($socket)) === FALSE)

            {

                 continue;

}

        else

            {

               socket_write($accept_socket, $res_content, $res_len);

               socket_close($accept_socket);

}

}

}

//Run as daemon process.

function run()

{

If(($pid1 = pcntl_fork()) === 0)

//First child process

{

            posix_setsid(); //Set first child process as the session leader.

If(($pid2 = pcntl_fork()) === 0)

​​​​ //Second child process, which run as daemon.

            {

                    //Replaced with your own domain or address.

                handle_http_request('www.codinglabs.org', 9999);

}

        else

            {

//First child process exit;

exit;

}

}

else

{

//Wait for first child process exit;

pcntl_wait($status);

}

}

//Entry point.

run();

?>

Here I assume that everyone is familiar with Unix environment programming, so I won't explain it in too many details, just sort it out. To put it simply, this program mainly consists of two parts. The handle_http_request function is responsible for processing http requests. Its writing method is similar to the tcp server written in C: create socket, bind, listen, and then process each connect through a loop. On the client side, once a connection is accepted, the fixed text "PHP HTTP Server" is output (of course the http header needs to be constructed first). Multiplexing and non-blocking are not considered here, but just a simple synchronous blocking tcp server.

The run function is responsible for turning the entire program into a daemon process. The method is very similar to the C method in the Unix environment. After two forks, setsid is called after the first fork to turn child process 1 into a session leader, so that child process 2 can be Unlike its ancestor detach, it will continue to run even if the ancestor process ends (leaved to the init process). I will not go into details. Friends who are not familiar with Unix processes can refer to the book "Advanced Programming in the UNIX Environment".

Note that here pcntl_fork corresponds to fork in Unix, pcntl_wait corresponds to wait, and posix_setsid corresponds to setsid. For more functions, please refer to the pcntl and fork modules in the PHP Manual.

Inspection

Start this script from the command line:

php httpserver.php

用ps命令可以看到我们已经启动了一个daemon进程:
 
Using the ps command you can see that we have started a daemon process:
1
1
How to use PHP to write daemon process_PHP tutorial
How to use PHP to write daemon process_PHP tutorial

What I bind here is the domain name of my blog, www.codinglabs.org, and the port is 9999, which can be modified as needed.

Next, I will use the curl command to see if the http server is running normally: How to use PHP to write daemon process_PHP tutorial

It seems that there is no problem. Let’s take a look in the browser: How to use PHP to write daemon process_PHP tutorial

Conclusion

Of course, this program is not a real http server. Even as a daemon process, it is imperfect. Many necessary things such as modifying the execution directory (which can be achieved through chroot in PHP), signal binding, logging functions, etc. are not available. Do it, but as a demo, it is enough to show that PHP can not only write dynamic web page processing scripts. If some friends are interested, you can use php to add the functions I mentioned above to this http server.

Another point to note is that the pcntl and sockets modules are not installed by default. If you do not specify installation through parameters when installing PHP, you need to install these two extension modules separately.

Excerpted from codinglabs.org

http://www.bkjia.com/PHPjc/478542.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/478542.htmlTechArticle
I saw a question on segmentfault.com this afternoon. The title of the question was how to implement PHP as a service, and it asked php Can it only be called via the web? In fact, many people have usage scenarios for PHP...
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