视野是生命的宽度,沉淀是生命的密度

未曾清贫难成人 不经打击老天真 自古英雄出炼狱 从来富贵入凡尘!

poll读取键盘鼠标,多路复用io

poll描述概要:
       #include <poll.h>
       int poll(struct pollfd *fds, nfds_t nfds, int timeout);


The set of file descriptors to be monitored is  specified  in  the  fds
argument, which is an array of structures of the following form:

 struct pollfd {
               int   fd;         /* file descriptor */
               short events;     /* requested events */
               short revents;    /* returned events */
           };


  The  bits that may be set/returned in events and revents are defined in
       <poll.h>:


              POLLIN There is data to read.


              POLLPRI
                     There is urgent data to read (e.g., out-of-band  data  on
                     TCP socket; pseudoterminal master in packet mode has seen
                     state change in slave).


              POLLOUT
                     Writing now will not block.


              POLLRDHUP (since Linux 2.6.17)
                     Stream socket peer closed connection, or shut down  writ‐
                     ing  half  of  connection.   The _GNU_SOURCE feature test
                     macro must be defined (before including any header files)
                     in order to obtain this definition.


              POLLERR
                     Error condition (output only).


              POLLHUP
                     Hang up (output only).


              POLLNVAL
                     Invalid request: fd not open (output only).


测试代码


#include <stdio.h>

#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <poll.h>

int main(void)
{
// 读取鼠标
int fd = -1, ret = -1;
char buf[200];
struct pollfd myfds[2] = {0};

fd = open("/dev/input/mouse1", O_RDONLY);
if (fd < 0)
{
perror("open:");
return -1;
}

// 初始化我们的pollfd
myfds[0].fd = 0; // 键盘
myfds[0].events = POLLIN; // 等待读操作

myfds[1].fd = fd; // 鼠标
myfds[1].events = POLLIN; // 等待读操作


ret = poll(myfds, fd+1, 10000);
if (ret < 0)
{
perror("poll: ");
return -1;
}
else if (ret == 0)
{
printf("超时了\n");
}
else
{
// 等到了一路IO,然后去监测到底是哪个IO到了,处理之
if (myfds[0].events == myfds[0].revents)
{
// 这里处理键盘
memset(buf, 0, sizeof(buf));
read(0, buf, 5);
printf("键盘读出的内容是:[%s].\n", buf);
}

if (myfds[1].events == myfds[1].revents)
{
// 这里处理鼠标
memset(buf, 0, sizeof(buf));
read(fd, buf, 50);
printf("鼠标读出的内容是:[%s].\n", buf);
}
}


return 0;
}
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24373811/article/details/52356189
上一篇O_NONBLOCK,fcntl 非阻塞io读取键盘鼠标
下一篇异步io
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭