我有一个接收服务器状态的检查点文件。此状态表示通过我的网络传递的序列化命令。
我正在尝试读取文件,但它卡在 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
在从文件描述符读取时遇到连接。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句