PHP is not suitable for a resident shell process in many cases, he does not have a dedicated GC routine, and does not have an effective memory management approach. So if you are using PHP as a resident shell, you will often be unhappy by memory exhaustion, causing abort.
Also, if the input data is illegal and the script is not detected, abort will make you unhappy.
That? What do we do?
Oh, don't worry, many processes to help you!
So, what is this for?
Advantages:
1. Using multiple processes, the kernel is responsible for reclaiming resources after the child process is finished
2. With multiple processes, a child process exception exit does not cause the entire process thread to exit. The parent process also has the opportunity to rebuild the process.
3. A permanent master process, which is responsible for the distribution of tasks, is more logically understood.
Then, what do you do?
Next, we implement a PHP command parser using the POSIX and PCNTL series functions provided by PHP, which is responsible for accepting user input, then fork the child process to execute, and is responsible for echoing the end state of the child process.
The code below, I added a note, if you do not understand the place, you can read the manual related functions, or reply to a message.
#!/bin/env PHP
/** A Example denoted muti-process application in PHP
* @filename fork.php
* @touch Date Wed June 10:25:51 PM CST
* @author Laruence
* @license http://www.zend.com/license/3_0.txt PHP License 3.0
* @version 1.0.0
*/
/** ensure that this function can only be run in the shell */
If
(Substr (Php_sapi_name (), 0, 3)!== ' CLI ')
{
Die ("This programe can is only is run in CLI mode");
}
/** the maximum execution event limit is turned off, in CLI mode, this statement is not necessary */
Set_time_limit (0);
$pid = Posix_getpid (); Get Master 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 (); Create Child process
If
($pid = = 0)
{//child process
$pid = Posix_getpid ();
Echo
"* Process {$pid} was created, and executed:\n\n";
eval ($input); Parse command
Exit
}
Else
{//Master process
$pid = pcntl_wait ($status, wuntraced); Get child process End state
If
(pcntl_wifexited ($status))
{
Echo
"\n\n* Sub process: {$return [' pid ']} exited with {$status}";
}
}
}
http://www.bkjia.com/PHPjc/752065.html www.bkjia.com true http://www.bkjia.com/PHPjc/752065.html techarticle PHP is not suitable for a resident shell process in many cases, he does not have a specific GC routine, and there is no efficient way to manage memory. So if you use PHP as a resident shell, you will often be run out of memory.