2、有名管道fifo 给文件系统提供一个路径,这个路径和管道关联,只要知道这个管道路径,就可以进行文件访问,fifo
是指先进先出,也就是先写入的数据,先读出来
3、有名管道的读写速度非常快
4、man 3 mkfifo
5、int mkfifo(const char *pathname, mode_t mode)
–参数*pathname:路径名,管道名称
–参数mode:管道的权限
–返回值:成功返回0,错误返回-1并更改errno的值。errno有可能出现的值为EACCESS EEXIST ENAMETOO-LONG ENOENT ENOENT ENOSPE ENOTDIR EROFS
例:
1、创建管道
#include<sys/types.h>
#include<sys/stat.h>
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
int main (int argc, char *argv[])
{
mode_t mode = 0666; /*新创建的FIFO模式*/
if(argc != 2) {
printf( "USEMS: create_fifo {fifoname}\n");
exit(1);
}
/*使用mkfifo()函数创建一个FIFO管道*/
if((mkfifo(argv[1],mode)) < 0) {
perror("fail to mkfifo");
exit(1);
}else{
printf("you successfully create a FIFO name is:%s\n",argv[1]);
}
exit(1);
}
2、FIFO 的读写操作
open函数参数flag标志位的O_NONBLOCK标志,它关系到函数的返回状态。
O_NONBLOCK
置位: 只读open立即返回。当只写open时,如果没有进程为读打开FIFO,则返回-1,并置errno值为ENXIO
不置位:open视情况阻塞。只读open要阻塞到进程为写打开FIFO,只写open要阻塞到有进程为读打开FIFO。
write_fifo.c
#include<sys/types.h>
#include<sys/stat.h>
#include<errno.h>
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdlib.h>
#include<limits.h>
#define BUFSZ PIPE_BUF
int main(void)
{
int fd;
int n,i;
char buf[BUFSZ];
time_t tp;
printf("I am %d\n",getpid());
if((fd = open("fifo1",O_WRONLY)) < 0 {
perror("open");
exit(1);
}
for(i = 0; i<10; i++) {
time(&tp);
n = sprintf(buf, "write_fifo %d sends %d", getpid(),ctime(&tp));
printf("send msg: %s\n",buf);
if((write(fd,buf,n+1)) < 0) {
perror("wrinte");
close(fd);
exit(1);
}
sleep(3);
}
close(fd);
exit(0);
}
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdlib.h>
#include<limits.h>
#define BUFSZ PIPE_BUF
int main(void)
{
int fd;
int n,i;
char buf[BUFSZ];
mode_t mode = 0666;
if((fd = open("fifo1",O_RDONLY)) < 0 {
perror("open");
exit(1);
}
while((len = read(fd,buf,BUFSZ)) > 0);
printf("read_fifo read :%s",buf);
close(fd);
exit(0);
}
$gcc write_fifo.c -o write_fifo
$gcc read_fifo.c -o read_fifo
$mkfifo -m 666 fifo1
$./write_fifo
I am 16414
Send msg :write_fifo 16414 sends Fri Mar 22 15:48:54 2013
$./read_fifo
read_fifo read:write_fifo 16414 sends Fri Mar 22 15:48:54 2013