多文件的读写

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>
#include <errno.h>
#include <string.h>

#define MAX_BUFFER_SIZE 1024
#define IN_FILES 3
#define TIME_DELAY 60
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define IN1 "/data/workspace/myshixun/case3/in1"
#define IN2 "/data/workspace/myshixun/case3/in2"

int main(void)
{
    int fds[IN_FILES];
    char buf[MAX_BUFFER_SIZE];
    int i, res, real_read, maxfd;
    struct timeval tv;
    fd_set inset, tmp_inset;

    fds[0] = 0;

    if ((fds[1] = open(IN1, O_RDONLY | O_NONBLOCK)) < 0)
    {
        printf("Open IN1 error.\n");
        return 1;
    }
    if ((fds[2] = open(IN2, O_RDONLY | O_NONBLOCK)) < 0)
    {
        printf("Open IN2 error.\n");
        return 1;
    }

    maxfd = MAX(fds[1], fds[2]);
    FD_ZERO(&inset);
    for (i = 0; i < IN_FILES; i++)
        FD_SET(fds[i], &inset);
    tv.tv_sec = TIME_DELAY;
    tv.tv_usec = 0;

    while (FD_ISSET(fds[0], &inset) || FD_ISSET(fds[1], &inset) || FD_ISSET(fds[2], &inset))
    {
        tmp_inset = inset;
        res = select(maxfd + 1, &tmp_inset, NULL, NULL, &tv); // Corrected select function call

        switch (res)
        {
        case -1:
        {
            printf("Select error\n");
            return 1;
        }
        break;
        case 0:
        {
            printf("Time out\n");
            return 1;
        }
        break;
        default:
            for (i = 0; i < IN_FILES; i++)
            {
                if (FD_ISSET(fds[i], &tmp_inset))
                {
                    memset(buf, 0, MAX_BUFFER_SIZE);
                    real_read = read(fds[i], buf, MAX_BUFFER_SIZE - 1); // Corrected read function call

                    if (real_read < 0)
                    {
                        if (errno != EAGAIN)
                            return 1;
                    }
                    else if (real_read == 0)
                    {
                        close(fds[i]);
                        FD_CLR(fds[i], &inset);
                    }
                    else
                    {
                        if (i == 0)
                        {
                            if ((buf[0] == 'q') || (buf[0] == 'Q'))
                                return 1;
                        }
                        else
                        {
                            buf[real_read] = '\0';
                            printf("%s", buf);
                        }
                    }
                }
            }
            break;
        }
    }

    return 0;
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值