Linux-异步IO
1.何为异步IO(1).几乎可以这么认为:异步IO就是操作系统用软件实现的一套中断响应系统.(2).异步IO的工作方法:我们当前进程注册一个异步IO事件(使用signal注册一个信号SIGIO的处理函数),然后当前进程可以正常处理自己的事情,当异步事件发生后当前进程会收到一个SIGIO信号从而执行绑定的处理函数去处理这个异步事件.2.涉及的函数:(1).fcntl(F_GETFL\F_SETFL\O_ASYNC\F_SETOWN)(2).signal或者sigaction(SIGIO)3.代码实例:#include <stdio.h>#include <unistd.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/select.h>
#include <signal.h>int mousefd = -1;
//绑定到SIGIO信号,在函数内处理异步通知事件
void func(int sig)
{
char buf;
if(sig != SIGIO)
return;
memset(buf, 0, sizeof(buf));
read(mousefd, buf, 2);
printf("读出的鼠标:[%s]\n",buf);
}int main(void)
{
int flag = -1;
char buf;
mousefd = open("/dev/input/mouse0",O_RDONLY);
if(mousefd < 0)
{
perror("open:");
return -1;
}
//注册异步通知(把鼠标的文件描述符设置为可以接受异步IO)
flag = 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));
read(0, buf, 5);
printf("读出的键盘:[%s]\n",buf);
}
return 0;
}
页:
[1]