首页 > 解决方案 > Read() 坚持尝试读取文件

问题描述

我有一个接收服务器状态的检查点文件。此状态表示通过我的网络传递的序列化命令。

我正在尝试读取文件,但它卡在了 read while 循环中。

我的阅读功能:

struct message_t *pmanager_readop(int fd){
    if (fd < 0) return NULL;

    // Variables
    char *buffer = NULL;
    int result, msg_size;
    struct message_t *msg;

    // Check if file has data
    lseek (fd, 0, SEEK_END);
    int size_ckp = lseek(fd, 0, SEEK_CUR);

    if (size_ckp <= 0)
        return NULL;

    // Read message size
    result = read_all(fd, (char *) &msg_size, 4);
    if (result < 0) {
        return NULL;
    }
    msg_size = ntohl(msg_size);
    // ............

我的 read_all() 函数:

int read_all(int sock, char *buf, int len){
    int bufsize = len;
    while(len > 0){
        int res = read(sock,buf,len);

        if(res < 0){
            if (errno == EINTR) continue;
            return res;
        }
        buf += res;
        len -= res;
    }
    return bufsize;
}

我使用相同的函数从我的服务器/客户端连接中读取数据,具有相同的序列化和格式但使用套接字描述符,并且它工作得很好。

标签: cfileio

解决方案


您应该处理read()返回的情况0,告诉您如果从套接字描述符读取,或者从文件描述符读取时遇到,则另一端关闭连接EOF


推荐阅读