日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

利用管道进行通信

發(fā)布時間:2025/3/17 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 利用管道进行通信 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

管道簡單介紹:

管道是單向的、先進(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; }





新人創(chuàng)作打卡挑戰(zhàn)賽發(fā)博客就能抽獎!定制產(chǎn)品紅包拿不停!

總結(jié)

以上是生活随笔為你收集整理的利用管道进行通信的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。