php如何实现多进程
PHP 多进程实现方法
PHP 实现多进程主要依赖于 pcntl 扩展和 posix 扩展。以下是几种常见的实现方式:
使用 pcntl_fork 创建子进程
pcntl_fork 是 PHP 中创建子进程的核心函数。调用后会返回一个进程 ID,父进程中返回子进程的 PID,子进程中返回 0。
$pid = pcntl_fork();
if ($pid == -1) {
die('Could not fork');
} elseif ($pid) {
// 父进程代码
pcntl_wait($status); // 等待子进程退出
} else {
// 子进程代码
exit(0); // 子进程退出
}
管理多个子进程
需要管理多个子进程时,可以循环创建并记录 PID:

$children = [];
for ($i = 0; $i < 5; $i++) {
$pid = pcntl_fork();
if ($pid == -1) {
die('Fork failed');
} elseif ($pid) {
$children[] = $pid;
} else {
// 子进程工作代码
sleep(1);
exit(0);
}
}
// 父进程等待所有子进程
foreach ($children as $pid) {
pcntl_waitpid($pid, $status);
}
使用进程池模式
对于需要控制并发数量的场景,可以使用进程池:
$maxWorkers = 3;
$workers = 0;
while ($work = getWork()) { // 假设有获取工作的函数
if ($workers >= $maxWorkers) {
pcntl_wait($status);
$workers--;
}
$pid = pcntl_fork();
if ($pid == -1) {
die('Fork failed');
} elseif ($pid) {
$workers++;
} else {
// 子进程处理工作
processWork($work);
exit(0);
}
}
// 等待剩余子进程
while (pcntl_waitpid(0, $status) != -1);
进程间通信
可以使用以下方式实现进程间通信:

- 共享内存:
shmop扩展 - 消息队列:
msg_*系列函数 - 管道:
posix_mkfifo - 信号:
pcntl_signal
示例使用信号处理:
pcntl_signal(SIGUSR1, function($signo) {
echo "Received signal $signo\n";
});
$pid = pcntl_fork();
if ($pid == 0) {
posix_kill(posix_getppid(), SIGUSR1);
exit(0);
}
pcntl_wait($status);
注意事项
pcntl扩展只能在 CLI 模式下使用,不适用于 Web 环境- 子进程会继承父进程的所有资源,需要注意资源释放
- 僵尸进程需要正确处理,避免资源泄漏
- Windows 系统不支持
pcntl扩展
对于更复杂的多进程管理,可以考虑使用以下替代方案:
- Symfony Process 组件
- ReactPHP 的 Child Process
- Amp 的 Parallel 功能






