当以非阻塞模式打开文件/ dev / urandom时,读取时仍然阻塞。 为什么阅读电话仍然阻塞。
#include #include #include #include #include #include #include #include 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。
显然,随机驱动程序总是考虑有数据可用,但不一定是快速交付。
/dev/urandom是非阻塞的设计 :
读取时, /dev/random设备将只在熵池中的估计的噪声位数内返回随机字节。 /dev/random应该适用于需要非常高质量随机性的应用,例如一次性密钥或密钥生成。 当熵池为空时,从/dev/random读取将被阻塞,直到收集到额外的环境噪声。
从/dev/urandom设备读取不会阻塞等待更多的熵。 因此,如果熵池中没有足够的熵,则返回的值理论上容易受到对驾驶员所使用的算法的密码攻击的影响。
如果你用/dev/random替换它,你的程序应该产生不同的结果。
在Linux中,无法以非阻塞模式打开常规文件。 您必须使用AIO接口以非阻塞模式从/ dev / urandom读取数据。