-
- #!/bin/env php
- /**A example denoted muti-process application in php
- * @filename fork.php
- * @edit bbs.it-home.org
- * @version 1.0.0
- */
- /**Make sure this function can only be run in SHELL*/
- if
- (substr(php_sapi_name(), 0, 3) ! == 'cli')
- {
- die("This Programe can only be run in CLI mode");
- }
- /**Turn off the maximum execution event limit. In CLI mode, this statement is actually unnecessary.*/
- set_time_limit(0);
- $pid = posix_getpid(); / /Get the main process ID
- $user = posix_getlogin(); //Get the 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)
- {//Subprocess
- $pid = posix_getpid();
- echo
- "* Process {$pid} was created, and Executed:nn";
- eval($input); //Parse the command
- exit;
- }
- else
- {//Main process
- $pid = pcntl_wait($status, WUNTRACED); //Get the end status of the child process
- if
- (pcntl_wifexited($status))
- {
- echo
- "nn* Sub process: {$return['pid']} exited with {$status}";
- }
- }
- }
- ?>
-
Copy the code
Please pay attention to the comments in the above code, which can help everyone understand and are also the essence of the code.
|