有名管道fifo
有名管道和无名管道基本相同,不同点在于无名管道用于父子进程之间通信,有名管道不相关的进程也能交换数据。
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char * pathname, mode_tmode)
pathname:FIFO文件名
mode:属性(见文件操作章节)
返回值:若成功则返回0,否则返回-1,错误原因存于errno中。
错误代码:
EACCESS 参数pathname所指定的目录路径无可执行的权限
EEXIST 参数pathname所指定的文件已存在。
ENAMETOOLONG 参数pathname的路径名称太长。
ENOENT 参数pathname包含的目录不存在
ENOSPC 文件系统的剩余空间不足
ENOTDIR 参数pathname路径中的目录存在但却非真正的目录。
EROFS 参数pathname指定的文件存在于只读文件系统内。
一旦创建了一个FIFO,就可用open打开它,一般的文件访问函数(close、read、write等)都可用于FIFO
1. 创建管道mkfifo
2. 打开管道open
3. 读管道read
4. 写管道write
5. 关闭管道close
6. 删除管道unlink
以 O_NONBLOCK的标志打开文件/socket/FIFO,如果连续做read操作而没有数据可读。此时程序不会阻塞起来等待数据准备就绪返回,read函数会返回一个错误EAGAIN,提示应用程序现在没有数据可读请稍后再试。
FIFO文件在使用上和普通文件有相似之处,但是也有不同之处:
Ø 读取fifo文件的进程只能以”O_RDONLY”方式打开fifo文件。
Ø 写fifo文件的进程只能以”O_WRONLY”方式打开fifo
Ø fifo文件里面的内容被读取后,就消失了。但是普通文件里面的内容读取后还存在。
1 //fifo_read.c 2 #include <sys/types.h> 3 #include <sys/stat.h> 4 #include <fcntl.h> 5 #include <errno.h> 6 #include <stdio.h> 7 #include <string.h> 8 #include <stdlib.h> 9 10 #define FIFO "/temp/fifofile" 11 12 int main() 13 { 14 int fd; 15 char buffer[1024] = {}; 16 17 if(mkfifo(FIFO, O_CREAT|O_EXCL) == -1) 18 perror("mkfifo error"); 19 20 fd = open(FIFO, O_RDONLY|O_NONBLOCK, 0); 21 if(fd == -1) 22 { 23 perror("open"); 24 exit(1); 25 } 26 27 while(1) 28 { 29 memset(buffer, 0, sizeof(char)*1024); 30 if(read(fd, buffer, 1024) == -1) 31 { 32 if(errno==EAGAIN) 33 { 34 printf("no data yet\n"); 35 } 36 } 37 else 38 { 39 printf("read %s from FIFO\n", buffer); 40 } 41 sleep(3); 42 } 43 44 unlink(FIFO); 45 46 return 0; 47 }
1 //fifo_write.c 2 #include <sys/types.h> 3 #include <sys/stat.h> 4 #include <fcntl.h> 5 #include <errno.h> 6 #include <stdio.h> 7 #include <string.h> 8 #include <stdlib.h> 9 10 #define FIFO "/temp/fifofile" 11 12 int main() 13 { 14 int fd; 15 char buffer[1024] = {}; 16 17 fd = open(FIFO, O_WRONLY|O_NONBLOCK, 0); 18 if(fd == -1) 19 { 20 perror("open fifo"); 21 exit(1); 22 } 23 24 while(1) 25 { 26 memset(buffer, 0, sizeof(char)*1024); 27 printf("puts:"); 28 scanf("%s", buffer); 29 30 if(write(fd, buffer, 1024) == -1) 31 { 32 printf("fifo data has not been read yet\n"); 33 } 34 printf("write data:%s\n", buffer); 35 } 36 37 return 0; 38 }