手机版
你好,游客 登录 注册
背景:
阅读新闻

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

[日期:2019-04-25] 来源:cnblogs.com/xiaoshiwang  作者:小石王 [字体:大 中 小]

调用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);
  }
}

Linux公社的RSS地址:https://www.linuxidc.com/rssFeed.aspx

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

linux
相关资讯       C/C++  open函数  C/C++ open函数 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款