read函数中判断EAGAIN
read函数是一个阻塞函数,当没有可读数据时会一直等待直到有数据到来。但是在某些情况下,我们需要设置为非阻塞模式,这时候就需要使用非阻塞IO,即设置文件描述符为非阻塞状态,这样当没有可读数据时,函数会立即返回一个错误码EAGAIN。
在读取数据时,如果出现EAGAIN错误码,表示当前没有可读数据,我们需要进行一些处理,比如等待一段时间再尝试读取,或者直接返回。
以下是一个示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
int main() {
int fd = open("test.txt", O_RDONLY | O_NONBLOCK);
if (fd == -1) {
perror("open failed");
exit(EXIT_FAILURE);
}
char buf[1024];
ssize_t nread;
while (1) {
nread = read(fd, buf, sizeof(buf));
if (nread == -1) {
if (errno == EAGAIN) {
printf("no data available\n");
sleep(1); // 等待1秒再尝试读取
continue;
} else {
perror("read failed");
exit(EXIT_FAILURE);
}
} else if (nread == 0) {
printf("end of file\n");
break;
} else {
printf("read %zd bytes: %.*s\n", nread, (int)nread, buf);
}
}
close(fd);
return 0;
}
``
原文地址: https://www.cveoy.top/t/topic/chYQ 著作权归作者所有。请勿转载和采集!