下面的应用程序等待/dev/globalvar_poll 可读,但是设置了 5 秒的等待超时,若超过 5 秒仍然没有数据可读,则输出“No data within 5 seconds”:
/* poll_read.c */
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
int fd, num;
fd_set rfds;
struct timeval tv;
fd = open("/dev/CDEV_ZHU", O_RDWR, S_IRUSR | S_IWUSR);
if (fd != -1)
{
while (1)
{
//查看 globalvar 是否有输入
FD_ZERO(&rfds);
FD_SET(fd, &rfds);
//设置超时时间为 5s
tv.tv_sec = 5;
tv.tv_usec = 0;
select(fd + 1, &rfds, NULL, NULL, &tv); //注:select 的文件描述符要加"1",最后一个参数设为“NULL”,则会永久等待
//数据是否可获得?
if (FD_ISSET(fd, &rfds))
{
read(fd, &num, sizeof(int));
printf("The globalvar is %d\n", num);
//输入为 0,退出
if (num == 0)
{
close(fd);
break;
}
}
else
printf("No data within 5 seconds.\n");
}
}
else
{
printf("device open failure\n");
}
return 0;
}
还需要另外一个应用程序进行写入,可以使用这篇文章“死锁”中的“globalvar_write.c”作为写入(见 http://www.linuxidc.com/Linux/2014-03/97437.htm )。测试结果如下:

