PHP 多进程编程 – 入门

本页内容

本文将简述如何快速了解 PHP 的多进程编程,并提供实验脚本。

函数

为快速入门,本文只使用多进程的两个函数:pcntl_forkpcntl_waitpid

多进程开发最重要的函数 pcntl_fork,其在当前进程 fork 一个子进程,然后父子进程在 fork 处分别继续向下执行。
这里需要注意,pcntl_fork 返回的值在父进程会得到子进程的 PID (进程 ID),而在子进程中,该值为 ``。

实例

接着开始实践,执行 pcntl.php 脚本:

 1$ php ./pcntl.php
 2
 3Child process #7217 started
 4Child process #7218 started
 5Child process #7218 finished
 6Child process #7220 started
 7Child process #7221 started
 8Child process #7219 started
 9Child process #7221 finished
10Child process #7217 finished
11Child process #7220 finished
12Child process #7219 finished
13Child process #7217 exited with status: 0
14Child process #7218 exited with status: 0
15Child process #7219 exited with status: 0
16Child process #7220 exited with status: 0
17Child process #7221 exited with status: 0

pcntl.php

 1<?php
 2
 3if (!extension_loaded('pcntl')) {
 4    die("Extension not loaded: pcntl\n");
 5}
 6
 7$workers = [];
 8$workersCount = 5;
 9
10for ($i = 0; $i < $workersCount; $i++) {
11    $pid = pcntl_fork();
12    if ($pid < 0) {
13        die("Could not fork\n");
14    }
15    if ($pid > 0) {
16        // parent process
17        $workers[] = $pid; // store child process ID.
18        continue;
19    }
20
21    // child process
22    $pid = posix_getpid();
23    echo "Child process #{$pid} started\n";
24
25    // task
26    sleep(rand(0, 2));
27
28    echo "Child process #{$pid} finished\n";
29
30    // exit on child process has finished it's task.
31    exit(0);
32}
33
34// parent process
35foreach ($workers as $worker) {
36    // wait child process to exit
37    pcntl_waitpid($worker, $status);
38    echo "Child process #{$worker} exited with status: {$status}\n";
39}
razonyang
2024年12月21日星期六 2019年1月6日星期日