目前在项目中想通过php的pcntl_fork来创建多个进程(比如8个)来并行消费redis队列消息。但运行日志发现并没有生成8个进程,而是2~3个。如下图:
//创建8个子进程
for ($i = 0; $i < 8; $i++) {
//fork子进程
$pid = pcntl_fork();
Logger::info("************ forked process id=" . $pid);
if ($pid == 0) {
$cid = $pid;
$pid = posix_getpid();
$ppid = posix_getppid();
$mypid = getmypid(); //pid 与mypid一样,是当前进程Id
Logger::info("************ child process cid=" . $cid . "|pid=" . $pid . "|ppid=" . $ppid . "|mypid=" . $mypid);
//拉取redis队列消息
$this->doWork();
Logger::info("************ work finished by pid=" . $pid);
exit(0);
}
}
private function doWork()
{
//循环
while (true) {
//pop redis msg
//...
}
}
日志打印显示出运行了8次
************ child process cid=0|pid=107070|ppid=107069|mypid=107070
************ child process cid=0|pid=107071|ppid=107069|mypid=107071
************ child process cid=0|pid=107072|ppid=107069|mypid=107072
************ child process cid=0|pid=107073|ppid=107069|mypid=107073
************ child process cid=0|pid=107074|ppid=107069|mypid=107074
************ child process cid=0|pid=107074|ppid=107069|mypid=107075
************ child process cid=0|pid=107074|ppid=107069|mypid=107076
************ child process cid=0|pid=107074|ppid=107069|mypid=107077
但实际上通过ps aux|grep php查看到的进程数并没有8个(只有3个107071,107072,107073):
23156 107071 0.0 0.0 112116 6832 pts/1 S 18:25 0:00 /usr/local/php/bin/php -f client.php
23156 107072 0.0 0.0 112116 6832 pts/1 S 18:25 0:00 /usr/local/php/bin/php -f client.php
23156 107073 0.0 0.0 112116 6848 pts/1 S 18:25 0:00 /usr/local/php/bin/php -f client.php
这是哪里不对?该如何修正?谢谢!