注解:borlittle
仅供学习参考,源代码版权归原著者所有<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />/*
* Buttons Example for utulinux 2440
* 一个简单的字符驱动程序测试程序
*/
#include <stdio.h> /*标准输入输出函数头文件*/
#include <stdlib.h> /*标准库文件定义头文件*/
#include <unistd.h> /*定义标准杂项的符号常量和类型,申明杂项的函数头文件*/
#include <sys/ioctl.h> /*特殊控制函数ioctl头文件,在系统目录的sys目录下*/
#include <sys/types.h> /*数据类型头文件*/
#include <sys/stat.h> /*定义fstat(), lstat(), and stat()函数的返回数据的结构头文件*/
#include <fcntl.h> /*文件控制操作头文件*/
#include <sys/select.h> /*查询监视文件描述符操作头文件*/
#include <sys/time.h> /*时间类型头文件*/
#include <errno.h> /*时间类型头文件*/
int main(void) /*主函数*/
{
int buttons_fd; /*文件句柄*/
int key_value; /*键值*/
buttons_fd = open("/dev/buttons", 0); /*打开驱动文件*/
if (buttons_fd < 0) { /*打开失败*/
perror("cann't open device /dev/buttons");
exit(1);
}
for (;;) { /*打开成功*/
fd_set rds; /*定义文件描述集变量*/
int ret;
/*
* FD_CLR(fd, &fdset)
* Clears the bit for the file descriptor fd in the file descriptor set fdset.
* FD_ISSET(fd, &fdset)
* Returns a non-zero value if the bit for the file descriptor fd is set in the file descriptor set pointed to by fdset, and 0 otherwise.
* FD_SET(fd, &fdset)
* Sets the bit for the file descriptor fd in the file descriptor set fdset.
* FD_ZERO(&fdset)
* Initialises the file descriptor set fdset to have zero bits for all file descriptors.
* http://www.opengroup.org/onlinepubs/7990989775/xsh/select.html
* fd_set是一组文件描述符(fd)的集合。由于fd_set类型的长度在不同平台上不同,
* 因此应该用一组标准的宏定义API来处理此类变量:
* fd_set set;
* /*FD_ZERO(&set); /*将set清零 */
* /*FD_SET(fd, &set); /* 将fd加入set */
* /*FD_CLR(fd, &set); /* 将fd从set中清除 */
* /*FD_ISSET(fd, &set); /* 如果fd在set中则真 */
* /*在过去,一个fd_set通常只能包含少于等于32个文件描述符,因为fd_set其实*/
* /*只用了一个int的比特矢量来实现,在大多数情况下,检查*/
* /*fd_set能包括任意值的文件描述符是系统的责任,但确定你*/
* /*的fd_set到底能放多少有时你应该检查/修改宏FD_SETSIZE的值*/
* /*这个值是系统相关的,同时检查你的系统中的select() 的man手册*/
* /*有一些系统对多于1024个文件描述符的支持有问题*/
* /*http://blog.chinaunix.net/u2/63316/showart_513811.html*/
*/
/*检测是否有输入*/
FD_ZERO(&rds); /* 将rds清零 */
FD_SET(buttons_fd, &rds); /* 将buttons_fd加入rds */
/*函数原型:int select(
int nfds, //监视的文件描述符加1
fd_set *readfds, //select监视的读文件描述符
fd_set *writefds, //select监视的写文件描述符
fd_set *errorfds, //select监视的错误文件描述符
struct timeval *timeout //等待超时时间
);
*/
ret = select(buttons_fd + 1, &rds, NULL, NULL, NULL);
if (ret < 0) { /* 没有读到数据 */
perror("select");
exit(1);
}
if (ret == 0) { /* 超时返回 */
printf("Timeout.\n");
} else if (FD_ISSET(buttons_fd, &rds)) /* 数据获取成功 */
{
int ret = read(buttons_fd, &key_value, sizeof key_value); /* 读取数据 */
if (ret != sizeof key_value) /* 检查读取到的键值*/
{
if (errno != EAGAIN) /* 无数据可读,继续等待按键*/
perror("read buttons\n");
continue;
} else
{ /* 读取成功,显示键值*/
printf("You pressed buttons %d\n", key_value);
}
}
}
/*关闭文件*/
close(buttons_fd);
return 0;
}
文章评论(0条评论)
登录后参与讨论