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

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

Netty 系列目录(http://www.javashuo.com/article/p-hskusway-em.html)函数

1、非阻塞式 IO

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

通常咱们在 open() 文件或打开文件后经过 iocntl() 或 fcntl() 函数都是使用设置是否采用阻塞方式打开。默认都是阻塞方式打开的,若是要使用非阻塞方式打开,则在须要显式的加入 O_NONBLOCK 标志htm

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

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

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

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

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

附:非阻塞式 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\n",argv[1]);
        return -1; 
    }   
 
    while(1) {   
        read(fd, buf, 1);    
        printf("buf = %d,  \n", buf[0]);
    }   
 
    close(fd);
    return 0;
}

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

相关文章
相关标签/搜索