zoukankan      html  css  js  c++  java
  • 【操作系统】编制实现进程的管道通信的程序

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

    使用系统调用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

  • 相关阅读:
    hihocoder 1388 Periodic Signal
    HDU 5880 Family View (AC自动机)
    HDU 5889 Barricade (bfs + 最小割)
    UVa 10806 Dijkstra, Dijkstra (最小费用流)
    POJ 3169 Layout (差分约束)
    差分约束系统学习
    HDU 3062 病毒侵袭持续中 (AC自动机)
    HDU 2896 病毒侵袭 (AC自动机)
    HDU 2222 Keywords Search (AC自动机)
    项目管理工具Leangoo,截止日期终于变绿色了
  • 原文地址:https://www.cnblogs.com/LPworld/p/14103991.html
Copyright © 2011-2022 走看看