pcntl_fork() 函数

https://php.golaravel.com/function.pcntl-fork.html
pcntl_fork — 在当前进程当前位置产生分支(子进程)。
译注:fork是创建了一个子进程,父进程和子进程 都从fork的位置开始向下继续执行,不同的是父进程执行过程中,得到的fork返回值为子进程 号,而子进程得到的是0。

for ($i = 0; $i < 3; $i++) {
    $pid = pcntl_fork();
    if ($pid > 0) {
        echo '父进程空间:'. $i .'-- 子进程ID:'. $pid. '-- 当前进程ID:'. posix_getpid() , "
";
    } else if ($pid == 0) {
        echo '子进程空间:'. $i .'-- 子进程ID:'. $pid. '-- 当前进程ID:'. posix_getpid(), "
";
    } else {
        echo '错误了', $pid, "
";
    }
}
sleep(30);
root@31e710224d20:/var/www/html# ps aux | grep pcntl
root       128  0.5  1.4 203620 28780 pts/0    S+   01:07   0:00 php swoole/server/pcntl.php
root       129  0.0  0.4 203620  8564 pts/0    S+   01:07   0:00 php swoole/server/pcntl.php
root       130  0.0  0.3 203620  7792 pts/0    S+   01:07   0:00 php swoole/server/pcntl.php
root       131  0.0  0.3 203620  7792 pts/0    S+   01:07   0:00 php swoole/server/pcntl.php
root       132  0.0  0.4 203620  8468 pts/0    S+   01:07   0:00 php swoole/server/pcntl.php
root       133  0.0  0.4 203620  8468 pts/0    S+   01:07   0:00 php swoole/server/pcntl.php
root       134  0.0  0.4 203620  8468 pts/0    S+   01:07   0:00 php swoole/server/pcntl.php
root       135  0.0  0.4 203620  8468 pts/0    S+   01:07   0:00 php swoole/server/pcntl.php
root       137  0.0  0.0  11112   980 pts/1    S+   01:07   0:00 grep pcntl
php swoole/server/pcntl.php
父进程空间:0-- 子进程ID:129-- 当前进程ID:128
子进程空间:0-- 子进程ID:0-- 当前进程ID:129
父进程空间:1-- 子进程ID:130-- 当前进程ID:128
父进程空间:1-- 子进程ID:131-- 当前进程ID:129
子进程空间:1-- 子进程ID:0-- 当前进程ID:131
子进程空间:1-- 子进程ID:0-- 当前进程ID:130
父进程空间:2-- 子进程ID:132-- 当前进程ID:128
子进程空间:2-- 子进程ID:0-- 当前进程ID:132
父进程空间:2-- 子进程ID:134-- 当前进程ID:130
父进程空间:2-- 子进程ID:133-- 当前进程ID:131
子进程空间:2-- 子进程ID:0-- 当前进程ID:133
父进程空间:2-- 子进程ID:135-- 当前进程ID:129
子进程空间:2-- 子进程ID:0-- 当前进程ID:134
子进程空间:2-- 子进程ID:0-- 当前进程ID:135
原文地址:https://www.cnblogs.com/smallyi/p/13894874.html