您的位置:首页 > 其它

高级IO(文件的读写)——阻塞式IO的困境、非阻塞式IO

2017-07-15 21:50 183 查看
以下内容源于朱有鹏《物联网大讲堂》课程的学习整理,如有侵权,请告知删除。

一、阻塞式IO的困境

1、程序中读取键盘

int main(void)
{
// 读取键盘
// 键盘就是标准输入,stdin

char buf[100];

memset(buf, 0, sizeof(buf));
printf("before read.\n");
read(0, buf, 5);
printf("读出的内容是:[%s].\n", buf);

return 0;
}




注意是行缓冲的,在输入回车时,才结束输入。

2、程序中读取鼠标

int main(void)
{
// 读取鼠标
int fd = -1;
char buf[200];

fd = open("/dev/input/mouse1", O_RDONLY);
if (fd < 0)
{
perror("open:");
return -1;
}

memset(buf, 0, sizeof(buf));
printf("before read.\n");
read(fd, buf, 50);
printf("读出的内容是:[%s].\n", buf);

return 0;
}




3、程序中同时读取键盘和鼠标

希望实现动键盘就显示键盘的内容,动鼠标就显示鼠标的内容;
但是下面的程序实际现象是:顺着程序先鼠标再键盘则顺利显示;先键盘的话,会被鼠标阻塞住。

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(void)
{
// 读取鼠标
int fd = -1;
char buf[200];

fd = open("/dev/input/mouse1", O_RDONLY);
if (fd < 0)
{
perror("open:");
return -1;
}

memset(buf, 0, sizeof(buf));
printf("before 鼠标 read.\n");
read(fd, buf, 50);
printf("鼠标读出的内容是:[%s].\n", buf);

// 读键盘
memset(buf, 0, sizeof(buf));
printf("before 键盘 read.\n");
read(0, buf, 5);//键盘就是标准输入,stdin,用0表示,它是默认打开的。
printf("键盘读出的内容是:[%s].\n", buf);

return 0;
}




二、非阻塞IO

1、阻塞的概念

阻塞:当前进程的执行条件不满足,内核将进程挂起,直到进程的执行条件满足。
linux在设计时,默认阻塞式。

2、为什么有阻塞式?

(1)常见的阻塞

4000

wait、pause、sleep等函数;
read或write某些文件时(read和write本身没有此属性,看读取对象是阻塞还是非阻塞的,比如键盘和鼠标就是阻塞式的)。

(2)阻塞式的好处

简单容易实现;
有利于充分发挥CPU的性能。

3、非阻塞

(1)为什么要实现非阻塞?

阻塞式IO的困境。

(2)如何实现非阻塞IO访问?

打开文件时添加O_NONBLOCK标志(非阻塞式);
或使用fcntl函数(可以普通地打开文件之后,再设置文件描述符的属性)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: