zoukankan      html  css  js  c++  java
  • pcntl扩展学习

    <?php 
    $i = 0;
        while($i < 3) {
            $pid = pcntl_fork();
            // 父进程和子进程都会执行以下代码
            if ($pid == -1) { // 创建子进程错误,返回-1
                die('could not fork');
            } else if ($pid) {
                // 父进程会得到子进程号,所以这里是父进程执行的逻辑
                pcntl_wait($status); // 父进程必须等待一个子进程退出后,再创建下一个子进程。
            
                $cid = $pid; // 子进程的ID
                $pid = posix_getpid(); // pid 与mypid一样,是当前进程Id
                $myid = getmypid();
                $ppid = posix_getppid(); // 进程的父级ID
                $time = microtime(true);
                echo "I am parent cid:$cid   myid:$myid pid:$pid ppid:$ppid i:$i $time 
    ";
            } else {
                // 子进程得到的$pid 为0,所以这里是子进程的逻辑
                $cid = $pid;
                $pid = posix_getpid();
                $ppid = posix_getppid();
                $myid = getmypid();
                $time = microtime(true);
                echo "I am child cid:$cid   myid:$myid pid:$pid ppid:$ppid i:$i  $time 
    ";
                //exit;
                //sleep(2);
            }
            $i++;
        }
    

      运行结果:

    I am child cid:0   myid:15 pid:15 ppid:14 i:0  1596186095.2482 
    I am child cid:0   myid:16 pid:16 ppid:15 i:1  1596186095.2488 
    I am child cid:0   myid:17 pid:17 ppid:16 i:2  1596186095.2493 
    I am parent cid:17   myid:16 pid:16 ppid:15 i:2 1596186095.2536 
    I am parent cid:16   myid:15 pid:15 ppid:14 i:1 1596186095.2577 
    I am child cid:0   myid:18 pid:18 ppid:15 i:2  1596186095.2582 
    I am parent cid:18   myid:15 pid:15 ppid:14 i:2 1596186095.2623 
    I am parent cid:15   myid:14 pid:14 ppid:8 i:0 1596186095.2664 
    I am child cid:0   myid:19 pid:19 ppid:14 i:1  1596186095.2669 
    I am child cid:0   myid:20 pid:20 ppid:19 i:2  1596186095.2674 
    I am parent cid:20   myid:19 pid:19 ppid:14 i:2 1596186095.2715 
    I am parent cid:19   myid:14 pid:14 ppid:8 i:1 1596186095.2756 
    I am child cid:0   myid:21 pid:21 ppid:14 i:2  1596186095.2761 
    I am parent cid:21   myid:14 pid:14 ppid:8 i:2 1596186095.2802
    
    运行结束,执行耗时:181毫秒
    

      

    待循环终止,子进程执行完毕,再执行父进程,再待循环终止,逐级执行。

    参考:https://segmentfault.com/a/1190000008955481

  • 相关阅读:
    Interview with BOA
    Java Main Differences between HashMap HashTable and ConcurrentHashMap
    Java Main Differences between Java and C++
    LeetCode 33. Search in Rotated Sorted Array
    LeetCode 154. Find Minimum in Rotated Sorted Array II
    LeetCode 153. Find Minimum in Rotated Sorted Array
    LeetCode 75. Sort Colors
    LeetCode 31. Next Permutation
    LeetCode 60. Permutation Sequence
    LeetCode 216. Combination Sum III
  • 原文地址:https://www.cnblogs.com/tdalcn/p/13410787.html
Copyright © 2011-2022 走看看