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

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

使用系统调用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!\n",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

 

posted @ 2020-12-08 17:53  海底淤泥  阅读(2089)  评论(0编辑  收藏  举报