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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值