小编use*_*328的帖子

Linux上以非阻塞模式读取文件

当以非阻塞模式打开文件 /dev/urandom 时,读取时它仍然是阻塞的。为什么 read 调用仍然阻塞。

#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));
    } …
Run Code Online (Sandbox Code Playgroud)

c linux random file-io posix

2
推荐指数
1
解决办法
4066
查看次数

标签 统计

c ×1

file-io ×1

linux ×1

posix ×1

random ×1