你好,游客 登录 注册 搜索
背景:
阅读新闻

驱动支持select函数

[日期:2014-03-01] 来源:Linux社区  作者:zhuyp1015 [字体:大 中 小]

下面的应用程序等待/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 )。测试结果如下:

linux
相关资讯       select函数 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款