命名管道
1.命名管道的創(chuàng)建
(1) 通過命令創(chuàng)建
mkfifo filename(2)在程序中創(chuàng)建
int mkfifo(const char* filename, mode_t mode);2. 命名管道和匿名管道的區(qū)別
????(1)匿名管道由pipe函數(shù)創(chuàng)建并且打開
????(2)命名管道有mkfifo函數(shù)創(chuàng)建由open函數(shù)打開
????(3) fifo 之間的兩個進程可以沒有血緣關系, 而 pipe 之間的兩個函數(shù)有血緣關系
3.代碼演示
//ClientPipe.c #include<stdio.h> #include<unistd.h> #include<string.h> #include<sys/stat.h> #include<sys/types.h> #include<fcntl.h> #include<stdlib.h>int main() {int wfd = open("mypipe", O_WRONLY);if(wfd == -1)//dakashibai{perror("open");exit(1);}char buf[1024];buf[0] = 0;ssize_t s;while(1){printf("Please Enter#");fflush(stdout);s = read(0, buf, sizeof(buf));if(s > 0)//成功讀取{buf[s] = 0;write(wfd, buf, s);}else if(s <= 0)//讀取失敗{perror("read");exit(1);}} } //ServerPipe.c #include<stdio.h> #include<unistd.h> #include<sys/stat.h> #include<fcntl.h> #include<stdlib.h> #include<sys/types.h>int main() {int fifo = mkfifo("mypipe", 0644);if(fifo == -1)//管道創(chuàng)建失敗{perror("mkfifo");exit(1);}//打開管道int rfd = open("mypipe", O_RDONLY);if(rfd == -1)//打開失敗{perror("open");exit(1);}//讀管道數(shù)據(jù)char buf[1024];ssize_t s;while(1){buf[0] = 0;printf("Please wait ... \n");s = read(rfd, buf, sizeof(buf) -1);if(s > 0)//讀到數(shù)據(jù){buf[s] = 0;printf("client say# %s", buf);}else if(s == 0)//讀完{printf("client quit, exit now\n");exit(0);}else//讀取失敗{perror("read");exit(1);}}close(rfd);return 0; }總結
- 上一篇: 你的名字我的姓氏剧情介绍
- 下一篇: 链表相关笔试面试题