单线程读fifo写文件

来源:互联网 发布:鬼谷战术风雨家淘宝 编辑:程序博客网 时间:2024/05/16 15:20
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;}


0 0
原创粉丝点击