How to write daemonprocess in PHP

Source: Internet
Author: User
Tags sapi
This afternoon, segmentfault.com asked a question about how PHP is servitized and whether php can only be called on the web. In fact, many people have misunderstandings about the use cases of PHP. they think that php can only be used to write web scripts. In fact, starting with PHP4, the use field of php... SyntaxHighlighter.

 

This afternoon, segmentfault.com asked a question titled "How to make PHP service", asking if php can only be called on the web. In fact, many people have misunderstandings about the use of PHP, and think that php can only be used to write web scripts. In fact, from PHP4, the use of php is no longer limited to processing web requests.

From the perspective of php architecture, php is divided into three layers: sapi, php core, and zend engine. Php core is not coupled with the web. php communicates with other applications through sapi. for example, mod_php is the sapi for apache. Similarly, fpm is an sapi implementation based on fastcgi protocol, these SAPIs work with web servers to process web requests. However, many SAPIs 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 am not going to discuss in detail the php architecture and sapi topics here. it just shows that from the perspective of the architecture system, php has already been designed to support various environments, rather than being unique to the web.

In addition to the support of the architecture system, the rich extension modules of php also provide the backend for php to play a role in different environments, for example, the pcntl module mentioned in this article can work with the posix module to implement basic process management, signal processing, and other operating system-level functions. The sockets module can make php capable of socket communication. Therefore, php can be used to write tool scripts similar to shell or perl, or even daemon process of server nature.

To demonstrate how to compile the daemon server in php, I wrote a simple http server in php, which runs in the form of daemon process. Of course, in order to focus on how to use php to write daemon, I did not implement specific business logic for this http server, but it can listen to the specified port, accept the http request and return a fixed text to the client. The entire process is implemented through socket, all written in php.

Code instance

The complete code of this program is as follows:

 

 

// 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 suppose you know more about programming in the Unix environment, so I will not explain it too much, just sort it out. To put it simply, this program is mainly composed of two parts. the handle_http_request function is responsible for processing http requests. the compiling method is similar to that of the tcp server written in C: creating socket, binding, and listening, then, each connect client is processed cyclically. Once the accept is connected, the fixed text "php http Server" is output (of course, the http header must be constructed first ), multiplexing and non-blocking are not considered here, but a simple synchronous blocking tcp server.

The run function is responsible for changing the entire program to daemon process. The method is similar to the C method in Unix environment. Two forks are used. after the first fork is used, setsid is called to change sub-process 1 to session leader, in this way, the child Process 2 and its ancestor detach can continue to run even if the ancestor process ends (the init process is left alone ). I will not repeat the details. if you are not familiar with Unix processes, refer to Advanced Programming in the UNIX Environment.

Note: pcntl_fork corresponds to fork in Unix, pcntl_wait corresponds to wait, and posix_setsid corresponds to setsid. for more functions, refer to pcntl and fork modules in PHP Manual.

Inspection

Run the following script on the command line:

 

php httpserver.php 

 

 

The ps command shows that we have started a daemon process:
1

Here I am binding my blog domain name www.codinglabs.org, Port is 9999, can be modified as needed.

Run the curl Command to check whether the http server is running properly:

It seems that there is no problem. let's look at it in the browser:

Conclusion

Of course, this program is not really an http server. even as a daemon process, it is not perfect. many necessary things, such as modifying the execution Directory (which can be implemented through chroot in php), signal binding, log functions, and so on, but as a demo, it is enough to indicate that php can not only write dynamic web page processing scripts. If you are interested, you can use php to add the functions I mentioned above to the http server.

Note that the pcntl and sockets modules are not installed by default. if you do not specify the installation parameters when installing php, you need to install these two extension modules separately.

 

From codinglabs.org

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.