单线程读fifo写文件
2015-12-01 16:52
148 查看
int log_fifo2file(char *fifoname, char *filename, size_t size, int expire, int *exitflag) { int fd1, fd2; size_t nread, nwrite, sum; char file[PATH_MAX], filenew[PATH_MAX], tmp[16]; char buffer[65536]; struct pollfd pfds[1]; int nfds; time_t create, now; struct stat st; struct tm tm; if(fifoname == NULL || filename == NULL) return EINVAL; /* open fifo */ mkfifo(fifoname, 0644); if(stat(fifoname, &st) != 0) return errno; if(!S_ISFIFO(st.st_mode)) return -1; if((fd1 = open(fifoname, O_RDWR|O_NONBLOCK, 0)) < 0) return errno; pfds[0].fd = fd1; pfds[0].events = POLLIN; /* open file */ snprintf(file, sizeof(file), "%s.tmp", filename); write: if((fd2 = open(file, O_WRONLY|O_NONBLOCK|O_CREAT, 0644)) < 0) return errno; create = time(NULL); sum = 0; /* read fifo, write file */ while(!*exitflag){ nfds = poll(pfds, 1, 1000); if(nfds <= 0) goto check; nread = read(fd1, buffer, sizeof(buffer)); if(nread < 0) continue; if(nread == 0) break; nwrite = write(fd2, buffer, nread); if(nwrite < 0) continue; sum += nwrite; check: now = time(NULL); if((size > 0 && sum > size) || (expire > 0 && now > create + expire)){ close(fd2); localtime_r(&now, &tm); sprintf(tmp, "%04d%02d%02d%02d%02d%02d", tm.tm_year+1900, tm.tm_mon+1,tm.tm_mday, tm.tm_hour, tm.tm_min, tm .tm_sec); snprintf(filenew, sizeof(filenew), "%s-%s.log", filename, tmp); rename(file, filenew); goto write; } } close(fd1); close(fd2); now = time(NULL); localtime_r(&now, &tm); sprintf(tmp, "%04d%02d%02d%02d%02d%02d", tm.tm_year+1900, tm.tm_mon+1,tm.tm_mday, tm.tm_hour, tm.tm_min, tm .tm_sec); snprintf(filenew, sizeof(filenew), "%s-%s.log", filename, tmp); rename(file, filenew); return 0; }
相关文章推荐
- 魔方阵
- bootstrap快速入门笔记(七)-表格,表单
- 美化的select下拉框
- QT自定义控件
- 模拟实现常用字符串函数
- AndroidStudio与GitHub
- Obj模型导入器实现
- hdoj Friendship of Frog 5578 (简单字符串转换)
- 数据链路层的是三个基本问题
- Selenium2Library源码解读(1)- 概述
- HBase系列三
- android中Scrollview中套ListView,高度超出屏幕,listview无法滑动问题
- 标准C的IO
- 九度OJ 1352:和为S的两个数字 (查找)
- 进程与线程的区别(面试高频问题)
- linux 多线程
- 汉诺塔问题
- MySQL碎碎念
- 九度OJ 1352:和为S的两个数字 (查找)
- ubuntu14.04 安装五笔输入法(fcitx)