Ai
1 Star 0 Fork 1

fortunely/linuxstudy

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
async.c 1.42 KB
一键复制 编辑 原始数据 按行查看 历史
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <signal.h>
#include <string.h>
#include <errno.h>
static void print_err(char *str, int line, int err_no) {
if (str != NULL) {
printf("line %d %s: %s\n", line, str, strerror(err_no));
exit(-1);
}
}
int mousefd = -1;
void signal_fun(int signo) {
if (signo == SIGIO) {
int buf = 0;
int ret = read(mousefd, &buf, sizeof buf);
if (ret < 0) print_err("read fail", __LINE__, errno);
else{
printf("%d\n", buf);
}
}
}
/**
* 异步IO例程: 阻塞读取键盘数据, 异步IO读取鼠标数据
*/
int main() {
mousefd = open("/dev/input/mouse1", O_RDONLY);
if (mousefd < 0) print_err("open mouse file fail", __LINE__, errno);
// 设置SIGIO信号捕获函数
signal(SIGIO, signal_fun);
// 告诉鼠标驱动: 当前进程接收并处理SIGIO信号
fcntl(mousefd, F_SETOWN, getpid());
// 设置当前进程读鼠标为异步IO方式
int flags = fcntl(mousefd, F_GETFL);
flags |= O_ASYNC;
fcntl(mousefd, F_SETFL, flags);
char buf[100];
while (1) {
memset(buf, 0, sizeof buf);
int n = read(STDIN_FILENO, buf, sizeof buf);
if (n < 0) print_err("read 0 fail", __LINE__, errno);
else {
printf("%s\n", buf);
}
}
return 0;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C
1
https://gitee.com/fortunely/linuxstudy.git
git@gitee.com:fortunely/linuxstudy.git
fortunely
linuxstudy
linuxstudy
master

搜索帮助