异步IO

来源:互联网 发布:赵泓霖网络课下载 编辑:程序博客网 时间:2024/06/10 03:23

《朱老师物联网大讲堂》学习笔记          

学习地址:www.zhulaoshi.org


异步IO,
可以理解为用软件实现的一套中断响应系统,


工作方法,
当前进程注册一个异步IO事件,使用signal注册一个信号SIGIO的处理函数,然后当前进程可以正常处理自己的事情,
当异步事件发生后当前进程会收到一个SIGIO信号从而执行绑定的处理函数去处理这个异步事件,


涉及函数,
fcntl,
signal 或 sigaction


老师课上示例代码,

 // 把鼠标的文件描述符设置为可以接受异步IO
 flag = fcntl(mousefd, F_GETFL);
 flag |= O_ASYNC;
 fcntl(mousefd, F_SETFL, flag);
 // 把异步IO事件的接收进程设置为当前进程
 fcntl(mousefd, F_SETOWN, getpid());
 
 // 注册当前进程的SIGIO信号捕获函数
 signal(SIGIO, func);

#include <stdio.h>#include <unistd.h>#include <string.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <signal.h>int mousefd = -1;// 绑定到SIGIO信号,在函数内处理异步通知事件void func(int sig){char buf[200] = {0};if (sig != SIGIO)return;read(mousefd, buf, 50);printf("鼠标读出的内容是:[%s].\n", buf);}int main(void){// 读取鼠标char buf[200];int flag = -1;mousefd = open("/dev/input/mouse1", O_RDONLY);if (mousefd < 0){perror("open:");return -1;}// 把鼠标的文件描述符设置为可以接受异步IOflag = fcntl(mousefd, F_GETFL);flag |= O_ASYNC;fcntl(mousefd, F_SETFL, flag);// 把异步IO事件的接收进程设置为当前进程fcntl(mousefd, F_SETOWN, getpid());// 注册当前进程的SIGIO信号捕获函数signal(SIGIO, func);// 读键盘while (1){memset(buf, 0, sizeof(buf));//printf("before 键盘 read.\n");read(0, buf, 5);printf("键盘读出的内容是:[%s].\n", buf);}return 0;}


0 0
原创粉丝点击