C/C++ open函数的阻塞和非阻塞


调用open函数时,可以指定是以阻塞方式还是以非阻塞方式打开一个文件描述符。

  • 阻塞方式打开:

int fd = open("/dev/tty", O_RDWR|O_NONBLOCK);

  • 非阻塞方式打开:

int fd = open("/dev/tty", O_RDWR);

C/C++ open函数的阻塞和非阻塞

例子:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>

int main(int argc, char* argv[]){
  int fd = open("/dev/tty", O_RDWR|O_NONBLOCK);
 
  char buf[256];
  while(1){
    int ret = read(fd, buf, sizeof buf);
    if(ret < 0){
      perror("read:");
      printf("ret :%d\n", ret);
    }
    printf("buf is:%s", buf);
    printf("haha\n");
  }
}

除了使用【O_NONBLOCK】外,还可以使用fcntl函数,原型如下:
#include <unistd.h>
#include <fcntl.h>

int fcntl(int fd, int cmd, ... /* arg */ );

F_GETFD (void)
  Return  (as  the function result) the file descriptor flags; arg
  is ignored.
F_SETFD (int)
  Set the file descriptor flags to the value specified by arg.


例子:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>

int main(int argc, char* argv[]){
  int fd = open("/dev/tty", O_RDWR);

  //先取得fd的flag
  int flags = fcntl(fd, F_GETFL);
  //再在原来fd的flag的基础上,设置上O_NONBLOCK
  flags |= O_NONBLOCK;
  //让新的flag生效
  fcntl(fd, F_SETFL, flags);
 
  char buf[256];
  while(1){
    int ret = read(fd, buf, sizeof buf);
    if(ret < 0){
      perror("read:");
      printf("ret :%d\n", ret);
    }
    printf("buf is:%s", buf);
    printf("haha\n");
    sleep(1);
  }
}

linuxboy的RSS地址:https://www.linuxboy.net/rssFeed.aspx

本文永久更新链接地址:https://www.linuxboy.net/Linux/2019-04/158300.htm

相关内容