[英]Read file in non-blocking mode on Linux
在非阻塞模式下打開文件/ dev / urandom時,它在讀取時仍處於阻塞狀態。 為什么讀取調用仍然阻塞。
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
int main(int argc, char *argv[])
{
int fd = open("/dev/urandom", O_NONBLOCK);
if (fd == -1) {
printf("Unable to open file\n");
return 1;
}
int flags = fcntl(fd, F_GETFL);
if (flags & O_NONBLOCK) {
printf("non block is set\n");
}
int ret;
char* buf = (char*)malloc(10000000);
ret = read(fd, buf, 10000000);
if (ret == -1) {
printf("Error reading: %s\n", strerror(errno));
} else {
printf("bytes read: %d\n", ret);
}
return 0;
}
輸出看起來像這樣:
gcc nonblock.c -o nonblock
./nonblock
non block is set
bytes read: 10000000
以非阻止模式打開任何(設備)文件並不意味着您不需要等待它。
O_NONBLOCK只是說如果沒有可用數據則返回EAGAIN。
顯然,urandom驅動程序始終認為有可用數據,但不一定很快就可以提供。
在Linux中,無法以非阻止模式打開常規文件。 您必須使用AIO接口以非阻塞模式從/ dev / urandom讀取。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.