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

  • 相关阅读:
    Java之JDBC操作
    Ubuntu17安装MySql5.7
    应用解决告诉你什么时候该用ajax
    jquery插件大全
    面试题:谈谈如何优化MYSQL数据库查询
    1亿条数据在PHP中实现Mysql数据库分表100张
    DEDECMS教程:首页实现分页的两种方法
    Dedecms当前位置{dede:field name='position'/}修改,去掉>方法
    mysql的MyISAM 和 InnoDB 的区别?优化MYSQL数据库的方法?
    COOKIE和SESSION关系和区别等
  • 原文地址:https://www.cnblogs.com/LPworld/p/14103991.html
Copyright © 2011-2022 走看看