c - Read() 尝试读取文件时卡住

标签 c file io

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

我正在尝试读取该文件,但它卡在了读取 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;
}

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

最佳答案

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

关于c - Read() 尝试读取文件时卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53469390/

相关文章:

c - 为什么我的缓冲区没有连接?

java.io : Rename all elements of an absolute File path

c++ - 通过查找位返回一个数组?

c - 段错误(核心已转储)- C 参数

linux - 如何使用 awk 显示文本文件中的重复项

asp.net - 在数据库或文件中保存长细节?

c - 使用 sscanf 迭代地解析字符串输入

c - 使用另一个宏生成#ifdef、#endif 子句

python - 在 Python 和 C 之间共享文件流

java - 就性能而言, `java.net` 和 `java.nio` 的替代方案是什么?