其实这个例子是从man 里面拷贝出来的。 稍加修改而已。
重要的一点是让我理解了这个函数的第一个参数一定要比想要询问的fd多1!
经过测试,select确实调用到了 file_operations 结构中的 poll。 这点和poll的机制是一样的。
/*
* =====================================================================================
*
* Filename: select.c
*
* Description: a small example for testing the select() function
*
* Version: 1.0
* Created: 11/25/2010 08:52:08 PM
* Revision: none
* Compiler: gcc
*
* Author: YOUR NAME (),
* Company:
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
int
main(void)
{
fd_set rfds;
struct timeval tv;
int retval;
int fd;
fd = open("/dev/scullpipe0", O_RDWR);
if (fd < 0)
{
perror("open()");
return -1;
}
/* Watch stdin (fd 0) to see when it has input. */
FD_ZERO(&rfds);
FD_SET(fd, &rfds);
/* Wait up to five seconds. */
tv.tv_sec = 5;
tv.tv_usec = 0;
retval = select(fd + 1
, &rfds, NULL, NULL, &tv);
/* Don't rely on the value of tv now! */
if (retval == -1)
perror("select()");
else if (retval)
printf("Data is available now./n");
/* FD_ISSET(0, &rfds) will be true. */
else
printf("No data within five seconds./n");
exit(EXIT_SUCCESS);
}