php多进程跑脚本

work.php主文件

#!/home/pay/odp/php/bin/php -c /home/pay/odp/php/etc/php.ini
<?php

/** 确保这个函数只能运行在SHELL中 */
if (substr(php_sapi_name(), 0, 3) !== ‘cli’) {
die(“This Programe can only be run in CLI mode”);
}
if (!function_exists(‘pcntl_fork’)) {
die(“pcntl_fork not existing”);
}

/** 关闭最大执行时间限制, 在CLI模式下, 这个语句其实不必要 */
set_time_limit(0);
/*
$pid = posix_getpid(); //取得主进程ID
$user = posix_getlogin(); //取得用户名
*/
$work_arr = array(
array(
‘file’ => ‘test.php’,
‘args’ => “arg1″,
),
array(
‘file’ => ‘test.php’,
‘args’ => “arg2″,
),
);
$process_arr = array();
foreach($work_arr AS $work){
$file = $work['file'];
$args = $work['args'];
if(!file_exists($file)){
continue;
}
$pid = pcntl_fork();
if($pis === -1){
echo “create process failed,file:{$file}\n”;
}elseif($pid == 0){//child process
$pid = posix_getpid();
$cmd = ‘/home/pay/odp/php/bin/php -c /home/pay/odp/php/etc/php.ini -q ‘.$file;
echo “* Process {$pid} was created, and Executed:\n\n”,$cmd.”\n\n”;
pcntl_exec(‘/home/pay/odp/php/bin/php’,array(‘-c /home/pay/odp/php/etc/php.ini’,$file),array(‘VAR_TEST’=>$args));
}else{//parent process
$process_arr[$file] = $pid;
}
}

//检查进程是否结束
$all_process_has_return = false;
$wait_options = WNOHANG;
while (!$all_process_has_return){
$all_process_has_return = true;//假设已经全部退出
foreach ($process_arr as $file => $pid){
$wait_ret = pcntl_waitpid($pid, $status, $wait_options);
if($wait_ret === 0){//只要还存在未退出的进程,已全部都退出就为false
$all_process_has_return = false;
}
}

}

?>

test.php为具体脚本

<?php
file_put_contents($_SERVER['VAR_TEST'].’_out.txt’,time());

?>

demo.php

参考资料:

http://ju.outofmemory.cn/entry/208177

此条目发表在 php 分类目录。将固定链接加入收藏夹。

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*


*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>