How to implement PHP multi-process in Linux

Source: Internet
Author: User
PHP multi-Process: use ProcessControlFunctions (PCNTL thread Control function) of PHP. if you need it, refer to PHP multi-Process: use Process Control Functions (PCNTL/thread Control function) of PHP)
Function Reference visible: http://www.php.net/manual/zh/ref.pcntl.php
It can only be used in Unix Like OS and Windows.
-Enable-pcntl must be added during php compilation. it is recommended that you only run in CLI mode instead of running in the WEB server environment.

The following is a simple PHP multi-process test code:

The code is as follows:


Declare (ticks = 1 );
$ BWaitFlag = FALSE; // whether to wait for the process to end
$ IntNum = 10; // process count
$ Pids = array (); // process PID array

Echo ("Start \ n ");

For ($ I = 0; $ I <$ intNum; $ I ++ ){

$ Pids [$ I] = pcntl_fork (); // generates sub-processes and starts the test run code from the current row without inheriting the data information of the parent process.

If (! $ Pids [$ I]) {
// Subprocess process code segment _ Start
$ Str = "";
Sleep (5 + $ I );
For ($ j = 0; $ j <$ I; $ j ++) {$ str. = "*";}
Echo "$ I->". time (). "$ str \ n ";
Exit ();
// Subprocess process code segment _ End
}

}
If ($ bWaitFlag)
{
For ($ I = 0; $ I <$ intNum; $ I ++ ){
Pcntl_waitpid ($ pids [$ I], $ status, WUNTRACED );
Echo "wait $ I->". time (). "\ n ";
}
}
Echo ("End \ n ");
?>

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.