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

阻塞方式打开:

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

非阻塞方式打开:

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

6051023a09a312f32a4750b8db11f2fd.png

例子:

#include

#include

#include

#include

#include

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

#include

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

#include

#include

#include

#include

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);

}

}

0b1331709591d260c1c78e86d0c51c18.png

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐