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;
}