非阻塞I/O

非阻塞I/O

非阻塞I/O使我们可以调用open、read和write这样的I/O操作,并使这些操作不会永远阻塞。如果这种操作不能完成,则调用立即出错返回,表示该操作若继续执行将阻塞。

对一个给定的描述符,有两种方法对其指定非阻塞I/O:

(1) 如果调用open获得描述符,则可指定O_NONBLOCK标志。

(2) 对于已经打开的一个描述符,则可调用fcntl,由该函数打开O_NONBLOCK文件状态标志。

示例程序:对一个文件描述符打开一个或多个文件状态标志

#include <stdio.h>
#include <fcntl.h>

void set_fl(int fd, int flags)  //flags are file status flags to turn on
{
     int val;
     if (val = fcntl(fd, F_GETFL, 0) < 0)
     {
           printf("fcntl F_GETFL error");
           return;
     }

      val |= flags;      //turn on flags
      if(fcntl(fd, F_SETFL, val) < 0)
      {
            printf("fcntl F_SETFL error");
            return;      
      }
}
原文地址:https://www.cnblogs.com/bettercoder/p/3505554.html