- 基本步骤:
- 使用
fcntl
函数获取文件描述符的当前标志。
- 使用
fcntl
函数设置文件描述符为非阻塞模式,通过在当前标志上添加O_NONBLOCK
标志。
- 进行I/O操作(如读或写),并检查返回值和错误码。如果返回值为 -1 且
errno
为EAGAIN
(或EWOULDBLOCK
,不同系统可能有别名),表示资源暂时不可用,需要稍后重试。
- 代码示例:
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#define BUFFER_SIZE 1024
int main() {
int fd;
char buffer[BUFFER_SIZE];
// 假设文件名为test.txt,打开文件
fd = open("test.txt", O_RDONLY);
if (fd == -1) {
perror("open");
return 1;
}
// 获取当前文件描述符标志
int flags = fcntl(fd, F_GETFL, 0);
if (flags == -1) {
perror("fcntl F_GETFL");
close(fd);
return 1;
}
// 设置为非阻塞模式
if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
perror("fcntl F_SETFL");
close(fd);
return 1;
}
// 进行读操作
ssize_t bytes_read = read(fd, buffer, sizeof(buffer));
if (bytes_read == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
printf("资源暂时不可用,稍后重试\n");
} else {
perror("read");
}
} else {
buffer[bytes_read] = '\0';
printf("读取到的数据: %s\n", buffer);
}
close(fd);
return 0;
}