【操作系統】編制實現進程的管道通信的程序


編制實現進程的管道通信的程序

使用系統調用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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM