利用管道进行通信
管道簡單介紹:
管道是單向的、先進(jìn)先出的、無結(jié)構(gòu)的、固定大小的字節(jié)流,它把一個進(jìn)程的標(biāo)準(zhǔn)輸出和還有一個進(jìn)程的標(biāo)準(zhǔn)輸入連接在一起。
寫進(jìn)程在管道的尾端寫入數(shù)據(jù)。讀進(jìn)程在管道的首端讀出數(shù)據(jù)。數(shù)據(jù)讀出后將從管道中移走。其他讀進(jìn)程都不能再讀到這些數(shù)據(jù)。管道提供了簡單的流控制機(jī)制。進(jìn)程試圖讀空管道時。在有數(shù)據(jù)寫入管道前,進(jìn)程將一直堵塞。相同,管道已經(jīng)滿時,進(jìn)程再試圖寫管道,在其他進(jìn)程從管道中移走數(shù)據(jù)之前,寫進(jìn)程將一直堵塞。
關(guān)于管道的代碼實(shí)例
此程序是關(guān)于管道的創(chuàng)建和讀寫和關(guān)閉 #include<unistd.h> #include<stdio.h> #include<stdlib.h>int main(void) {int fd[2];char str[256];if( pipe(fd) < 0 ){perror("pipe");exit(1);}write(fd[1],"create the pipe successfully!\n ",31);read(fd[0],str,sizeof(str));printf("%s",str);printf("pipe file descriptors are %d ,%d\n",fd[0],fd[1]);close(fd[0]);close(fd[1]); return 0; }此程序說明管道內(nèi)的數(shù)據(jù)在讀出之后就沒有了 #include<stdio.h> #include<unistd.h> int main() {int filedes[2];char buffer[20];pipe(filedes);if( fork()> 0){char s[]="hello\n";write(filedes[1],s,sizeof(s));} else{read(filedes[0],buffer,80);printf("%s\n",buffer);}read(filedes[0],buffer,80);printf("%s\n",buffer);close(filedes[0]);close(filedes[1]);return 0; }父子進(jìn)程之間的通過管道進(jìn)行通信 #include<unistd.h> #include<stdio.h> #include<fcntl.h> #include<sys/types.h>int main() {int fd[2];char buf[20];pid_t pid;int len;if( pipe(fd) < 0 ){perror("failed to pipe;");return 1;}if( ( pid = fork() ) < 0 ){perror("failed to fork;");return 1;}else if( pid > 0 ){close(fd[0]);write(fd[1],"hello my son\n",14);return 0;}else {close(fd[1]);read(fd[0],buf,20);printf("%s\n",buf); }return 0; }
兄弟進(jìn)程之間進(jìn)行通信 要點(diǎn):須要在第二次創(chuàng)建一個子進(jìn)程的時候關(guān)閉父進(jìn)程管道的兩端, 而不是第一次,這樣做的目的是繼承一個存活的管道。
#include<unistd.h> #include<stdio.h> #include<stdlib.h> #include<fcntl.h> #include<sys/types.h> int main( void ) { int fd[2]; char buf[100]; pid_t pid; int len; if( pipe(fd) < 0 ) perror("pipe"); if( ( pid = fork() ) < 0) perror("fork1"); else if( pid == 0 ) { close(fd[0]); write(fd[1],"hello brother!",20); exit(0); } if( ( pid = fork() ) < 0) perror("fork2"); else if( ( pid > 0 ) < 0) { close(fd[0]); close(fd[1]); exit(0); } else { close(fd[1]); read(fd[0],buf,20); printf("%s\n",buf); } return 0; }
總結(jié)
- 上一篇: 如何用SQL语句查询Excel数据
- 下一篇: Basic Calculator II