• 【操作系统】编制实现进程的管道通信的程序


    编制实现进程的管道通信的程序

    使用系统调用pipe()建立一条管道线,两个子进程分别向管道写一句话:

    Child process 1 is sending a message! 

    Child process 2 is sending a message! 

    而父进程则从管道中读出来自于两个子进程的信息,显示在屏幕上。

    要求:父进程先接收子进程P1发来的消息,然后再接收子进程P2发来的消息。

    代码:

    #include<stdio.h>
    #include<stdlib.h>
    #include<signal.h>
    #include<unistd.h>
    #define NUM 2 
    int pid[NUM+1],fd[2],i,ri;
    char S[40];//string
    void mysend(){//child send message
        sprintf(S,"Child process %d is sending a message!
    ",i);
        write(fd[1], S, 40);//write pipe
        kill(pid[0],17);//send signal to father
        exit(0);
    }
    void myreceive(){//father receive message
        read(fd[0], S, 40);//read pipe
        printf("%s",S);//show message
        if(i<NUM)kill(pid[++i],17);//send signal to next child
        else{while(wait(NULL)!=-1);exit(0);}//no next child so end
    }
    void fatherfun(){//father process
        i=1;
        signal(17,myreceive);//sign
        kill(pid[i],17);//send signal
        while(1);//wait
    }
    void childfun(){//child process
        signal(17,mysend);//sign
        while(1);//wait
    }
    int main(){
        pipe(fd);//build pipe
        pid[0]=getpid();//save father pid
        for(i=2;i<=NUM;i++)if(pid[i]=fork()){if(i==NUM)fatherfun();}else{childfun();break;}//make child
        return 0;
    }

    参考:

    https://www.cnblogs.com/leeming0222/articles/3994125.html

    https://blog.csdn.net/httpdrestart/article/details/80744352?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromBaidu-1.control&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromBaidu-1.control

    https://blog.csdn.net/xuzhangze/article/details/79829723

    https://www.cnblogs.com/Cqlismy/p/13053970.html

  • 相关阅读:
    django第10天(聚合查询,常用字段)
    django第9天(多表操作)
    django第8天(在测试文件中运行django项目|单表操作)
    django第七天(模板的复用性,include标签和母版)
    django第六天(模板相关,过滤器和标记)
    SparkCore2
    SparkCore
    SQL
    Spark基础
    使用Observer实现HBase到Elasticsearch的数据同步
  • 原文地址:https://www.cnblogs.com/LPworld/p/14103991.html
Copyright © 2020-2023  润新知