目录
理论
在int mkfifo(const char *pathname, mode_t mode)
成功返回o,出错返回-1
他包含在头文件:
#include <sys/types.h>
#include <sys/stat.h>
这里要注意:
1.只要对FIFO有适当的访问权限,FIFO可用在任何两个没有任何关系的进程之间通信;
2.本质是内核中的一块缓存,另在文件系统中以一个特殊的设备文件(管道文件)存在;
3.在文件系统中只有一个索引块存放文件的路径,没有数据块,所有数据存放在内核中;
4.命名管道必须在读和写中同时打开,否则单独读或者单独写会发生阻塞;
5.命令mkfifo创建命名管道(命令内部调用mkfifo函数)
6.对FIFO的操作与操作普通文件一样;
例子
程序运行截图如下:
fifo_read.c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <memory.h>
int main(int argc, char *argv[]){
if(argc < 2){
printf("usage:%s fifo\n", argv[0]);
exit(1);
}
printf("open fifo read... \n");
int fd = open(argv[1], O_RDONLY);
if(fd < 0){
perror("open error");
exit(1);
}
else{
printf("open file success:%d\n", fd);
}
//从命名管道中读取数据
char buf[512];
memset(buf, 0, sizeof(buf));
while(read(fd, buf, sizeof(buf)) < 0){
perror("read error");
}
printf("%s\n", buf);
close(fd);
exit(0);
}
fifo_write.c源码如下:
#include <unistd.h>
#include <memory.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
int main(int argc, char *argv[]){
if(argc < 2){
printf("usage:%s fifo\n", argv[0]);
exit(1);
}
printf("open fifo write ... \n");
//打开命名管道
int fd = open(argv[1], O_WRONLY);
if(fd < 0){
perror("open error");
exit(1);
}
else{
printf("open fifo success:%d\n", fd);
}
char *s = "12345678901234";
size_t size = strlen(s);
if(write(fd, s, size) != size){
perror("write error");
}
close(fd);
exit(0);
}
这里要创建一个pip,命令如下:mkfifo s.pipo