创建命名管道
命名管道可以从命令行上创建
mkfifo filename
命名管道也可以从程序里创建
int mkfifo(const char *filename, mode_t mode);
//创建命名管道
int main(){
mkfifo("fifo", 0644);
return 0;
}
匿名管道与命名管道的区别
- 匿名管道由pipe函数创建并打开
- 命名管道由mkfifo函数创建,用open打开
- FIFO(命名管道)与pipe(匿名管道)之间唯一的区别在他们创建与打开的方式不同,一旦这些工作完成后,它们具有相同的意义。
命名管道的打开规则
1)如果当前打开操作是为读而打开FIFO时
- O_NONBLOCK disable:阻塞直到有相应进程为写而打开该FIFO
- O_NONBLOCK enable:立即返回成功
2)如果当前打开操作是为写而打开FIFO时
- O_NONBLOCK disable:阻塞直到有相应进程为读而打开该FIFO
- O_NONBLOCK enable:立即返回失败,错误码为ENXIO
命名管道实现进程间通信
writer.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
int main(){
int fd = open("./myfifo", O_WRONLY);
if(fd < 0){
perror("open error");
return 1;
}
while(1){
char buf[1024] = {0};
printf("Please Enter:");
fflush(stdout);
ssize_t read_size = read(0, buf, sizeof(buf) - 1);
if(read_size < 0){
perror("read error");
return 1;
}
if(read_size == 0){
printf("read done!\n");
return 0;
}
buf[read_size] = '\0';
write(fd, buf, strlen(buf));
}
close(fd);
return 0;
}
reader.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
int main(){
int fd = open("./myfifo", O_RDONLY);
if(fd < 0){
perror("open error");
return 1;
}
while(1){
char buf[1024] = {0};
printf("Please wait ...\n");
ssize_t read_size = read(fd, buf, sizeof(buf) - 1);
if(read_size < 0){
perror("read error");
return 1;
}
if(read_size == 0){
printf("read done!\n");
return 0;
}
buf[read_size] = '\0';
printf("client say# %s", buf);
}
close(fd);
return 0;
}
效果如下:
详细代码请参考Git(点击Git即可)