PHP-php实现多进程

PHP-php实现多进程

归属感 发布于 2017-10-13 字数 26 浏览 1165 回复 2

php如何启用多进程?

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浮生未歇 2017-11-08 2 楼

用PHP实现多进程(多任务)
/**
*基于PHP5实现
*借助proc_open
*能启动多进程,你可以使用你的想象力做你想做的了
*如果你是在linux上跑php,并且启用pcntl模块后,使用pcntl函数该更好
**/

<?php
error_reporting(E_ALL);
set_time_limit(0);

class Thread {
protected $_pref; // process reference
protected static $_instance = null;
protected $_pipes;

private function __construct() {
$this->_pref = 0;
}

public static function getInstance($file) {
if (null == self::$_instance) {
self::$_instance = new self;
}

$descriptor = array(
0 => array("pipe", "r"),
1 => array("pipe", "w"),
2 => array("file", "./error-output.txt", "a"),
);
self::$_instance->_pref = proc_open("php -q $file", $descriptor, self::$_instance->_pipes);
return true;
}

public function __destruct() {
proc_close($this->_pref);
$this->_pref = null;
}
}
// 测试代码
$file = __FILE__;
if(emptyempty($argv[1])) {
$t2 = Thread::getInstance("$file 1");
$t3 = Thread::getInstance("$file 2");
$t4 = Thread::getInstance("$file 3");
$t5 = Thread::getInstance("$file 4");
$t5 = Thread::getInstance("$file 5");
$t5 = Thread::getInstance("$file 6");
$t2 = Thread::getInstance("$file 7");
$t3 = Thread::getInstance("$file 8");
$t4 = Thread::getInstance("$file 9");
$t5 = Thread::getInstance("$file 10");
$t5 = Thread::getInstance("$file 11");
$t5 = Thread::getInstance("$file 12");
echo "Main thread donen";
} else {
$somecontent = "//~~~~~~~~~~~~-这次请求序号是:" . $argv[1];
sleep(mt_rand(0, 3));
$handle = fopen($file, 'a+');
fwrite($handle, $somecontent);
}

泛泛之交 2017-11-03 1 楼

首先在ubuntu下编译pcntl.so,我的ubuntu下找不到pcntl的包,于是
创建一个文件夹下载了整个PHP包,在里面找到了pcntl包运行如下命令

mkdir php
cd php
apt-get source php5
cd php5-(WHATEVER_RELEASE)/ext/pcntl
phpize
./configure

然后将编译好的pcntl.so复制到系统php的拓展文件夹下,具体位置看phpinfo

 cp modules/pcntl.so /usr/lib/php5/WHEVER_YOUR_SO_FILES_ARE/

echo "extension=pcntl.so" > /etc/php5/conf.d/pcntl.ini

查看phpinfo可以看到已经加载了pcntl

2,开始pcntl_fork

 <?php

//while(1)//循环采用3个进程
$bWaitFlag = FALSE; // 是否等待进程结束
//$bWaitFlag = TRUE; // 是否等待进程结束
$intNum = 3; // 进程总数
$pids = array(); // 进程PID数组

for($i = 0; $i <$intNum; $i++) {

$pids[$i] = pcntl_fork();// 产生子进程,而且从当前行之下开试运行代码,而且不继承父进程的数据信息
if($pids[$i] == -1) {
echo "couldn't fork". "n";
}elseif(!$pids[$i]) {
sleep(1);
echo "n"."第".$i."个进程 -> " . time(). "n";
//$url=" http://xxx/comments.php?p=".$i;//抓取页面的例子
//$content = file_get_contents($url);
//file_put_contents('message.txt',$content);
//echo "n"."第".$i."个进程 -> " ."抓取页面".$i."-> " . time()."n";
exit(0);//子进程要exit否则会进行递归多进程,父进程不要exit否则终止多进程
}
if ($bWaitFlag) {
pcntl_waitpid($pids[$i], $status, WUNTRACED);echo "wait $i -> " . time() . "n";
}
}

?>

保存为fork.php 在命令行运行 php fork.php