本文共 2282 字,大约阅读时间需要 7 分钟。
1、无名管道只能用于有亲缘关于的进程通信,有名管道可以实现无亲缘关系的通信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、创建管道
#include2、FIFO 的读写操作#include #include #include #include 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);}
open函数参数flag标志位的O_NONBLOCK标志,它关系到函数的返回状态。
O_NONBLOCK 置位: 只读open立即返回。当只写open时,如果没有进程为读打开FIFO,则返回-1,并置errno值为ENXIO 不置位:open视情况阻塞。只读open要阻塞到进程为写打开FIFO,只写open要阻塞到有进程为读打开FIFO。write_fifo.c
#includeread_fifo.c#include #include #include #include #include #include #include #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#include #include #include #include #include #include #include #define BUFSZ PIPE_BUFint 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转载地址:http://aynws.baihongyu.com/