管道實驗(一)
阿新 • • 發佈:2018-12-24
編寫程式實現以下功能:
利用匿名管道實現父子程序間通訊,要求父程序傳送字串“hello child”給子程序;
子程序收到父程序傳送的資料後,給父程序回覆“hello farther”
父子程序通訊完畢,父程序依次列印子程序的退出狀態以及子程序的pid。
管道作為較為原始的程序間的通訊方式,在程序間的通訊中被廣泛使用。管道可分為有名管道和匿名管道,兩者有相似之處又有一定的區別。
匿名管道的特點如下:
1.匿名管道是半雙工的,資料只能朝一個放向流動,因此要實現兩個程序的通訊,就必須建立兩個匿名管道;
2.匿名管道只能在管道尾部寫入資料,從管道頭部讀取資料;fd[0]用於程序讀取資料,fd[1]用於程序寫入資料;
3.匿名管道不具備儲存資料的能力,資料一旦被讀取,其它程序將不能從該管道中讀取資料;
4.匿名管道只能在有血緣關係的程序間通訊;如父子程序和兄弟程序。
程式如下:
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> int main() { int fd1[2],fd2[2]; pipe(fd1); pipe(fd2); int pid; pid = fork(); if(pid < 0) perror("fork"); else if(pid == 0) { close(fd1[0]); close(fd2[1]); char str[12]; printf("This is the child!\n"); if(read(fd2[0],str,12) > 0) { printf("Received the news: %s\n",str); if(write(fd1[1],"hello father",12) < 0) perror("write"); } else perror("read"); exit(5); } else { int status; printf("This is the father!\n"); close(fd1[1]); close(fd2[0]); char buf[24] = "hello child"; if(write(fd2[1],buf,12) < 0) perror("write"); else { printf("Send news successful!\n"); } wait(&status); if(WIFEXITED(status)) { printf("The child's pid is: %d\n",pid); printf("The child's exited status is: %d\n",WEXITSTATUS(status)); } } return 0; }
程式結果: