本文將簡述如何快速瞭解 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}