1. 程式人生 > >linux select檢測多按鍵demo

linux select檢測多按鍵demo

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <fcntl.h>
#include <errno.h>
#include <time.h>
#include <linux/input.h>
#include <sys/select.h>

int main ()
{
	int keys_fd0,keys_fd1;
	char ret[2];
	struct input_event t;
	int maxfd;
	fd_set readfds;
	struct timeval tv;
	
	tv.tv_sec = 0; //秒
    tv.tv_usec = 10000; //微妙
	keys_fd0 = open ("/dev/input/event0", O_RDONLY);
	if (keys_fd0 <= 0)
	{
		printf ("open /dev/input/event0 device error!\n");
		return 0;
	}
	keys_fd1 = open ("/dev/input/event1", O_RDONLY);
	if (keys_fd1 <= 0)
	{
		printf ("open /dev/input/event1 device error!\n");
		return 0;
	}
	maxfd = 1+((keys_fd0>keys_fd1)?keys_fd0:keys_fd1);

	for(;;)
	{
		FD_ZERO(&readfds); //每次迴圈都要清空集合,否則不能檢測描述符變化
		FD_SET(keys_fd0,&readfds); //新增描述符
		FD_SET(keys_fd1,&readfds); //同上
		switch(select(maxfd,&readfds,NULL,NULL,&tv)) //select使用
		{
			case -1: exit(-1);break; //select錯誤,退出程式
			case 0: break; //再次輪詢
			default:
				if(FD_ISSET(keys_fd0,&readfds))
				{
					read (keys_fd0,&t, sizeof (t));
					if (t.type == EV_KEY)
					{
						if (t.value == 0)
						{
							printf("0\n");
						} // end if
						if(t.code==KEY_ESC)
								break;
				} // end if
			}
		if(FD_ISSET(keys_fd1,&readfds))
		{
			read (keys_fd1,&t, sizeof (t));
			if (t.type == EV_KEY)
			{
				if (t.value == 0)
				{
					printf("0\n");
				}
			if(t.code==KEY_ESC)
				break;
			}	
		}
	}// end switch
	}
	close (keys_fd1);
	close (keys_fd0);
	return 0;
}