Linux-异步IO

1.何为异步IO

(1).几乎可以这么认为:异步IO就是操作系统用软件实现的一套中断响应系统.

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

2.涉及的函数:

(1).fcntl(F_GETFLF_SETFLO_ASYNCF_SETOWN)

(2).signal或者sigaction(SIGIO)

3.代码实例:

 1 #include <stdio.h>
 2 #include <unistd.h>
 3 #include <string.h>
 4 #include <sys/time.h>
 5 #include <sys/types.h>
 6 #include <sys/stat.h>
 7 #include <fcntl.h>
 8 #include <sys/select.h>
 9 #include <signal.h>
10 
11 int mousefd = -1;
12 //绑定到SIGIO信号,在函数内处理异步通知事件
13 void func(int sig)
14 {
15     char buf[200];
16     if(sig != SIGIO)
17         return;
18     memset(buf, 0, sizeof(buf));
19     read(mousefd, buf, 2);
20     printf("读出的鼠标:[%s]
",buf);
21 }
22 
23 int main(void)
24 {
25     int flag = -1;
26     char buf[100];
27     mousefd = open("/dev/input/mouse0",O_RDONLY);
28     if(mousefd < 0)
29     {
30         perror("open:");
31         return -1;
32     }
33     
34     //注册异步通知(把鼠标的文件描述符设置为可以接受异步IO)
35     flag = fcntl(mousefd, F_GETFL);
36     flag |= O_ASYNC;
37     fcntl(mousefd, F_SETFL, flag);
38     
39     //把异步IO事件的接收进程设置为当前进程
40     fcntl(mousefd, F_SETOWN, getpid());    
41     
42     //注册当前进程的SIGIO信号捕获函数
43     signal(SIGIO, func);
44     
45     //读键盘
46     while(1)
47     {
48         memset(buf, 0, sizeof(buf));
49         read(0, buf, 5);
50         printf("读出的键盘:[%s]  
",buf);        
51     }
52     return 0;
53 }
原文地址:https://www.cnblogs.com/jiangtongxue/p/11289388.html