c - 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;
}
我使用相同的函数从我的服务器/客户端连接中读取数据,具有相同的序列化和格式但使用套接字描述符,并且它工作得很好。
解决方案
您应该处理read()
返回的情况0
,告诉您如果从套接字描述符读取,或者从文件描述符读取时遇到,则另一端关闭连接EOF
。
推荐阅读
- excel - Excel VBA 更改单元格颜色
- google-app-engine - 为 Google App Engine 转换 pfx 文件
- internet-explorer-11 - IE11 重定向后忽略 X-Frame-Options
- c# - 如何使用ajax将模型值从上一页传递到新页面发布方法?
- oracle - 在连接条件下使用 CASE 更新 PL/SQL?
- android - 使用 DownloadManager 下载 PDF 文件
- javascript - Flutter:在读取 Firebase 数据时进行异步操作
- node.js - AWS Lambda GraphicsMagick 错误:找不到 gm/convert 二进制文件”
- bash - /etc/passwd Bash Shell 的输出
- c# - 如何将值截断到一定的小数位数?