1.命名管道的創建
(1) 通過命令創建
mkfifo filename
(2)在程序中創建
int mkfifo(const char* filename, mode_t mode);
2. 命名管道和匿名管道的區別
????(1)匿名管道由pipe函數創建并且打開
????(2)命名管道有mkfifo函數創建由open函數打開
????(3) fifo 之間的兩個進程可以沒有血緣關系, 而 pipe 之間的兩個函數有血緣關系
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)//管道創建失敗{perror("mkfifo");exit(1);}//打開管道int rfd = open("mypipe", O_RDONLY);if(rfd == -1)//打開失敗{perror("open");exit(1);}//讀管道數據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)//讀到數據{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;
}