国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Backend Development PHP Tutorial How to use PHP to write daemon process_PHP tutorial

How to use PHP to write daemon process_PHP tutorial

Jul 13, 2016 pm 05:47 PM
php process use exist how write

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命令可以看到我們已經(jīng)啟動了一個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...
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to get the current session ID in PHP? How to get the current session ID in PHP? Jul 13, 2025 am 03:02 AM

The method to get the current session ID in PHP is to use the session_id() function, but you must call session_start() to successfully obtain it. 1. Call session_start() to start the session; 2. Use session_id() to read the session ID and output a string similar to abc123def456ghi789; 3. If the return is empty, check whether session_start() is missing, whether the user accesses for the first time, or whether the session is destroyed; 4. The session ID can be used for logging, security verification and cross-request communication, but security needs to be paid attention to. Make sure that the session is correctly enabled and the ID can be obtained successfully.

PHP get substring from a string PHP get substring from a string Jul 13, 2025 am 02:59 AM

To extract substrings from PHP strings, you can use the substr() function, which is syntax substr(string$string,int$start,?int$length=null), and if the length is not specified, it will be intercepted to the end; when processing multi-byte characters such as Chinese, you should use the mb_substr() function to avoid garbled code; if you need to intercept the string according to a specific separator, you can use exploit() or combine strpos() and substr() to implement it, such as extracting file name extensions or domain names.

How do you perform unit testing for php code? How do you perform unit testing for php code? Jul 13, 2025 am 02:54 AM

UnittestinginPHPinvolvesverifyingindividualcodeunitslikefunctionsormethodstocatchbugsearlyandensurereliablerefactoring.1)SetupPHPUnitviaComposer,createatestdirectory,andconfigureautoloadandphpunit.xml.2)Writetestcasesfollowingthearrange-act-assertpat

How to split a string into an array in PHP How to split a string into an array in PHP Jul 13, 2025 am 02:59 AM

In PHP, the most common method is to split the string into an array using the exploit() function. This function divides the string into multiple parts through the specified delimiter and returns an array. The syntax is exploit(separator, string, limit), where separator is the separator, string is the original string, and limit is an optional parameter to control the maximum number of segments. For example $str="apple,banana,orange";$arr=explode(",",$str); The result is ["apple","bana

JavaScript Data Types: Primitive vs Reference JavaScript Data Types: Primitive vs Reference Jul 13, 2025 am 02:43 AM

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

Using std::chrono in C Using std::chrono in C Jul 15, 2025 am 01:30 AM

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

How to pass a session variable to another page in PHP? How to pass a session variable to another page in PHP? Jul 13, 2025 am 02:39 AM

In PHP, to pass a session variable to another page, the key is to start the session correctly and use the same $_SESSION key name. 1. Before using session variables for each page, it must be called session_start() and placed in the front of the script; 2. Set session variables such as $_SESSION['username']='JohnDoe' on the first page; 3. After calling session_start() on another page, access the variables through the same key name; 4. Make sure that session_start() is called on each page, avoid outputting content in advance, and check that the session storage path on the server is writable; 5. Use ses

How does PHP handle Environment Variables? How does PHP handle Environment Variables? Jul 14, 2025 am 03:01 AM

ToaccessenvironmentvariablesinPHP,usegetenv()orthe$_ENVsuperglobal.1.getenv('VAR_NAME')retrievesaspecificvariable.2.$_ENV['VAR_NAME']accessesvariablesifvariables_orderinphp.iniincludes"E".SetvariablesviaCLIwithVAR=valuephpscript.php,inApach

See all articles