zoukankan      html  css  js  c++  java
  • 第7章 进程关系(2)_进程链和进程扇

    2. 进程链和进程扇

    (1)创建进程链

      ①进程链:就是父进程创建一个子进程,创建的子进程再次创建出属于自己的子进程,这样依次往下循环,如下图所示。

     

      ②关键实现:判断出如果是父进程则退出,保证父进程只会创建一个子进程。如果是子进程继续创建接下来的进程再退出。

    【编程实验】构建进程链

    //process_link.c

    #include <unistd.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(int argc, char* argv[])
    {
        int counter = (argc < 2 ) ? 2 : atoi(argv[1]);
        
        pid_t pid;
        int i = 0;
        //构建进程链
        for(i = 1; i<counter; i++) {
            pid = fork();
            if(pid < 0 ){
                perror("fork error");
                exit(1);
            }else if(pid == 0) { //子进程继续,以进一步创建子进程形成进程链
                continue;
            }else{ //父进程退出循环
                break;
            }
        }
    
        printf("pid: %d, ppid = %d
    ", getpid(), getppid());
        
        wait(0);
    }

    (2)创建进程扇

      ①进程扇:就是一个父进程创建出多个子进程,如下图所示。

     

      ②关键实现:判断出子进程则退出创建子进程的循环把创建进程的机会只留给父进程

    【编程实验】构建进程扇

    //process_swing.c

    #include <unistd.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(int argc, char* argv[])
    {
        int counter = (argc < 2 ) ? 2 : atoi(argv[1]);
        
        pid_t pid;
        int i = 0;
        //构建进程扇
        for(i = 1; i<counter; i++) {
            pid = fork();
            if(pid < 0 ){
                perror("fork error");
                exit(1);
            }else if(pid == 0) { //子进程则退出
                break;
            }else{ //父进程继续创建子进程
                continue;
            }
        }
    
        printf("pid: %d, ppid = %d
    ", getpid(), getppid());
        
        for(i=0; i<counter; i++)
            wait(0);   
    }
  • 相关阅读:
    程序由多个文件组成时、 头文件
    c++ 数组,变量,指针,引用, 初始化,赋值
    linux 远程装机
    linux中firewall与iptables防火墙服务
    linu samba服务
    linux 中iscsi服务
    Linux中apache服务
    linux dns高速缓存
    linux 网络配置
    linux 数据库管理
  • 原文地址:https://www.cnblogs.com/5iedu/p/6358320.html
Copyright © 2011-2022 走看看