PHP is often not suitable for resident shell processes, he does not have a dedicated GC routines, and there is no effective memory management path. So if you're using PHP as a resident shell, you'll often run out of memory and lead to abort and unhappy
Moreover, if the input data is illegal, and the script is not detected, causing abort, it will also make you very unhappy.
That? What do we do?
Multi-process ....
Why, then?
Advantages:
1. With multiple processes, the kernel is responsible for reclaiming resources after the child process finishes
2. Using multiple processes, the exception of a subprocess exit does not cause the entire process thread to exit. The parent process also has the opportunity to rebuild the process.
3. A resident main process, which is only responsible for the distribution of tasks, has a clearer logic
Then, how do you do it?
Next, we use the POSIX and PCNTL series functions provided by PHP to implement a PHP command parser that accepts user input and then executes the fork subprocess and is responsible for echoing the end state of the child process.
Code as follows, I added a note, if there is no understanding of the place, you can read the manual related functions, or reply to the message.
The code is as follows:
#!/bin/env PHP
-->/** A Example denoted muti-process application in PHP
* @filename fork.php
* @touch Date Wed June 2009 10:25:51 PM CST
* @author Laruence
* @license http://www.zend.com/license/3_0.txt PHP License 3.0
* @version 1.0.0
*/
/** Make sure that this function only runs in the shell.
if (substr (Php_sapi_name (), 0, 3)!== ' CLI ') {
Die ("This programe can is run in CLI mode");
}
/** the maximum execution time limit is turned off, in CLI mode, this statement is not actually necessary.
Set_time_limit (0);
$pid = Posix_getpid (); Get main Process ID
$user = Posix_getlogin (); Get user Name
Echo <<
USAGE: [Command expression]
Input PHP code to execute by fork a new process
Input quit to exit
Shell Executor version 1.0.0 by laruence
EOD;
while (true) {
$prompt = "\n{$user}$";
$input = ReadLine ($prompt);
Readline_add_history ($input);
if ($input = = ' quit ') {
Break
}
Process_execute ($input. ';');
}
Exit (0);
function Process_execute ($input) {
$pid = Pcntl_fork (); To create a child process
if ($pid = = 0) {//child process
$pid = Posix_getpid ();
echo "* Process {$pid} was created, and executed:\n\n";
eval ($input); Parsing commands
Exit
} else {//main process
$pid = pcntl_wait ($status, wuntraced); To get the end state of a child process
if (pcntl_wifexited ($status)) {
echo "\n\n* Sub process: {$pid} exited with {$status}";
}
}
}
But one thing I must remind:
The code is as follows:
Process Control should not is enabled within a webserver environment and unexpected results may happen if any process Cont Rol functions are used within a webserver environment. --from PHP, that is to say, eliminate the idea of using multiple processes in PHP Web development!