出自朱有鹏老师的课堂
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <poll.h>
#include <sys/types.h>
#include <unistd.h>
int main(void)
{
// 读取鼠标
int fd = -1;
int ret = -1;
char buf[200];
struct pollfd myfds[2] = {0}; //当前有两组fd,所以数组的大小是2
fd = open("/dev/input/mouse1", O_RDONLY); //fd打开鼠标,打开之后得到鼠标的文件描述符,要用root权限
if (fd < 0)
{
perror("open:");
return -1;
}
// 初始化pollfd
myfds[0].fd = 0; // 键盘
myfds[0].events = POLLIN; // POLLIN是读,等待读操作
myfds[1].fd = fd; // 鼠标
myfds[1].events = POLLIN; // POLLIN是读,等待读操作
ret = poll(myfds, fd+1, 10000); //select经过调用就会被阻塞,等待鼠标或者键盘的响应,如下:
if(ret < 0) //出错了
{
perror("poll:");
return -1;
}
else if(ret == 0) //超时了
{
printf("超时了.\n");
}
else //大于0
{
// 等到了其中的一路IO,然后去检测到底是哪一路的IO到了,然后处理她
if(myfds[0].events == myfds[0].revents)
{
// 处理键盘
memset(buf, 0, sizeof(buf));
//printf("before 键盘 read.\n");
read(0, buf, 5);
printf("键盘读出的内容是:[%s].\n", buf);
}
if(myfds[1].events == myfds[1].revents)
{
// 处理鼠标
memset(buf, 0, sizeof(buf));
//printf("before 鼠标 read.\n");
read(fd, buf, 50);
printf("鼠标读出的内容是:[%s].\n", buf);
}
}
return 0;
}