Linux NIO 系列(03) 非阻塞式 IO

Linux NIO 系列(03) 非阻塞式 IO

Netty 系列目录(https://www.cnblogs.com/binarylei/p/10117436.html)

一、非阻塞式 IO

阻塞和非阻塞 I/O 是设备访问的两种不同模式,驱动程序可以灵活地支持这两种用户空间对设备的访问方式。

一般我们在 open() 文件或打开文件后通过 iocntl() 或 fcntl() 函数都是使用设置是否采用阻塞方式打开。默认都是阻塞方式打开的,如果要使用非阻塞方式打开,则在需要显式的加入 O_NONBLOCK 标志

在 BSD 套接字编程中,似乎将文件描述符设置为非阻塞 I/O 模式的推荐方式是使用 PLACEHOLDER_FOR_CODE_l 标志到 fcntl(),例如:

int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, flags | O_NONBLOCK);

在 UNIX 使用 FIONBIO ioctl() 调用来执行此操作:

int opt = 1;
ioctl(fd, FIONBIO, &opt);

非阻塞方式访问的方式中,最常见的就是轮询方式,即不停的轮询 IO 是否可用,当可用时再读取。当然不停通过读来轮询的方式并不是好的方式。系统把这个功能交给了 select 和 poll 系统调用来实现了。

附:非阻塞式 IO 编程

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
 
int main(int argc,char *argv[]) {
    char buf[2];
    
    /* 非阻塞方式打开 */
    int fd = open("/dev/button", O_RDWR | O_NONBLOCK);
 
    if(fd < 0) {   
        printf("open /dev/%s fail
",argv[1]);
        return -1; 
    }   
 
    while(1) {   
        read(fd, buf, 1);    
        printf("buf = %d,  
", buf[0]);
    }   
 
    close(fd);
    return 0;
}

每天用心记录一点点。内容也许不重要,但习惯很重要!

原文地址:https://www.cnblogs.com/binarylei/p/11123399.html