PHP在很多時候不適合做常駐的SHELL進(jìn)程, 他沒有專門的gc例程, 也沒有有效的內(nèi)存管理途徑. 所以如果用PHP做常駐SHELL, 你會經(jīng)常被內(nèi)存耗盡導(dǎo)致abort而unhappy.
而且, 如果輸入數(shù)據(jù)非法, 而腳本沒有檢測, 導(dǎo)致abort, 也會讓你很不開心.
那? 怎么辦呢?
多進(jìn)程….
為什么呢?
優(yōu)點(diǎn):
1. 使用多進(jìn)程, 子進(jìn)程結(jié)束以后, 內(nèi)核會負(fù)責(zé)回收資源
2. 使用多進(jìn)程,子進(jìn)程異常退出不會導(dǎo)致整個進(jìn)程Thread退出. 父進(jìn)程還有機(jī)會重建流程.
3. 一個常駐主進(jìn)程, 只負(fù)責(zé)任務(wù)分發(fā), 邏輯更清楚
Then, 怎么做呢?
接下來, 我們使用PHP提供的POSIX和Pcntl系列函數(shù), 來實(shí)現(xiàn)一個PHP命令解析器, 主進(jìn)程負(fù)責(zé)接受用戶輸入, 然后fork子進(jìn)程執(zhí)行, 并負(fù)責(zé)回顯子進(jìn)程的結(jié)束狀態(tài).
代碼如下, 我加了注釋, 如果有不懂的地方, 可以翻閱手冊相關(guān)函數(shù), 或者回復(fù)留言.
復(fù)制代碼 代碼如下:
#!/bin/env php
<?php
/** A example denoted muti-process application in php
* @filename fork.php
* @touch date Wed 10 Jun 2009 10:25:51 PM CST
* @author Laruence<laruence@baidu.com>
* @license PHP License 3.0
* @version 1.0.0
*/
/** 確保這個函數(shù)只能運(yùn)行在SHELL中 */
if (substr(php_sapi_name(), 0, 3) !== 'cli') {
die("This Programe can only be run in CLI mode");
}
/** 關(guān)閉最大執(zhí)行時間限制, 在CLI模式下, 這個語句其實(shí)不必要 */
set_time_limit(0);
$pid = posix_getpid(); //取得主進(jìn)程ID
$user = posix_getlogin(); //取得用戶名
echo <<<EOD
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(); //創(chuàng)建子進(jìn)程
if ($pid == 0) {//子進(jìn)程
$pid = posix_getpid();
echo "* Process {$pid} was created, and Executed:/n/n";
eval($input); //解析命令
exit;
} else {//主進(jìn)程
$pid = pcntl_wait($status, WUNTRACED); //取得子進(jìn)程結(jié)束狀態(tài)
if (pcntl_wifexited($status)) {
echo "/n/n* Sub process: {$pid} exited with {$status}";
}
}
}
復(fù)制代碼 代碼如下:
Process Control should not be enabled within a webserver environment and unexpected results may happen if any Process Control functions are used within a webserver environment. --摘自PHP手也就是說, 打消你在PHP Web開發(fā)中使用多進(jìn)程的念頭吧!
新聞熱點(diǎn)
疑難解答