pcntl_fork 与swoole中的process对比,请看PHP扛把子之一韩大牛的说明
废话不多说,先来个swoole基本的进程操作,直接代码:
$process = new swoole_process(function($worker){
echo "子进程".$worker->pid;
});
$pid = $process->start(); //返回pid,和pcntl_fork()执行一样
进程的执行分为回调函数和匿名函数两种:
//回调函数
$process = new swoole_process('callBack_process');
$process->start();
function callBack_process($worker){
echo "子进程执行".$worker->pid;
}
//匿名函数
$process = new swoole_process(function($worker){
echo "子进程".$worker->pid;
});
$pid = $process->start();
swoole_process::wait():回收结束运行的子进程。通过设置参数true或false可以设置是否阻塞等待,默认为阻塞(true)
//以多进程执行为列
for($i=0,$workernum=4; $i<$workernum; $i++){
$process = new swoole_process('callBack_process');
$process->start();
}
function callBack_process($worker){
echo "子进程执行".$worker->pid.PHP_EOL;
}
while(true){
$res = swoole_process::wait();
if($res){
echo PHP_EOL;
var_dump($res);
}else{
break;
}
}
swoole_process::signal():设置异步信号监听。同步阻塞的程序可以使用pcntl扩展提供的pcntl_signal
for($i=0,$num=4;$i<$num;$i++){
$process = new swoole_process(function($worker){
echo "子进程".$worker->pid;
});
$process->start();
}
swoole_process::signal(SIGCHLD, function($sig){
while(true){
$res = swoole_process::wait(false);
if($res){
var_dump($res);
}else{
break;
}
}
});
swoole_process管道通信:
$url = [
"www.baidu.com",
"www.360.cn",
"blog.diligentyang.com",
];
$result = [];
for($i=0,$num=3;$i<$num;$i++){
$process = new swoole_process(function($worker)use($i,$url){
echo "子进程".$worker->pid;
echo $worker->read().PHP_EOL;
$res = curlTest($url[$i]); //执行curl操作
$worker->write($res); //向管道内写入数据
});
$pid = $process->start();
$process->write('子进程执行 curl');
$result[] = $process->read(); //读取管道数据
}
var_dump($result);
function curlTest($url){
sleep(rand(5,10));
return "执行curl".$url;
}
while(true){
$res = swoole_process::wait(false);
if($res){
var_dump($res);
}else{
break;
}
}
swoole_process队列:
$process = new swoole_process(function($worker){
$data = $worker->pop();
echo "读取队列".$data.PHP_EOL;
});
$process->useQueue();
$process->start();
$process->push('hello message!!'); //写入队列
while(true){
$res = swoole_process::wait();
if($res){
var_dump($res);
}else{
break;
}
}
以上就是swoole_process 的基本使用,本人才疏学浅,还望有人能多多拍砖。
网友评论