在C ++中的ifstream上设置超时? [英] Setting a timeout on ifstream in C++?

查看:93
本文介绍了在C ++中的ifstream上设置超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正试图从连接到Linux盒的2个USB鼠标中读取数据(此数据用于机器人上的里程表/本地化).因此,我们需要不断从每只鼠标读取其移动量.问题在于,当鼠标不动时,它不会发送任何数据,因此从中获取数据块的文件流将因此而执行,因此该程序无法进行里程表计算(这涉及到速度的时间测量)

We're trying to read data from 2 usb mice connected to a linux box (this data is used for odometry/localization on a robot). So we need to continuously read from each mouse how much it moved. The problem is that when a mouse is not moving, it doesn't send any data, so the file stream from which we get the data blocks execution and therefore the program can't do the odometry calculations (which involve time measurement for speed).

是否可以在输入流上设置超时(我们在C ++中使用ifstream并从/dev/input/mouse中读取),因此我们能够知道何时鼠标不动,而不是等待事件被接收?还是我们需要弄乱线程(arggh ...)?欢迎其他任何建议!

Is there a way to set a timeout on the input stream (we're using ifstream in C++ and read from /dev/input/mouse), so that we're able to know when the mouse doesn't move, instead of waiting for an event to be received? Or do we need to mess up with threads (arggh...)? Any other suggestions are welcome!

提前谢谢!

推荐答案

从linux中读取多个文件描述符的一种常见方法是使用select().我建议从联机帮助页开始.基本系统流程如下:

A common way to read from multiple file descriptors in linux is to use select(). I suggest starting with the manpage. The basic system flow is as follows:

1)初始化设备
2)获取设备文件描述符列表
3)设置超时时间
4)以文件描述符和超时作为参数调用select-它会阻塞直到其中一个文件描述符上有数据或达到超时
5)确定为什么要返回select并采取相应措施(即,对具有数据的文件描述符调用read()).您可能需要在内部缓冲读取结果,直到获得整个数据报为止.
6)循环回到4.

1) Initialize devices
2) Obtain list of device file descriptors
3) Setup the time out
4) Call select with file descriptors and timeout as parameters - it will block until there is data on one of the file descriptors or the time out is reached
5) Determine why select returned and act accordingly (i.e. call read() on the file descriptor that has data). You may need to internally buffer the result of read until an entire data gram is obtained.
6) loop back to 4.

这可以成为您的程序主循环.如果您已经有一个不同的主循环,则可以在不循环的情况下运行上述操作,但是您需要确保足够频繁地调用该函数,以免串行端口上的数据丢失.您还应该确保您的更新速率(即1/超时)对于您的主要任务而言足够快.

This can become your programs main loop. If you already have a different main loop you, can run the above without looping, but your will need to insure that the function is called frequently enough such that you do not lose data on the serial ports. You should also insure that your update rate (i.e. 1/timeout) is fast enough for your primary task.

Select可以对任何文件描述符(例如网络套接字)以及通过文件描述符公开接口的任何其他文件进行操作.

Select can operate on any file descriptor such network sockets and anything else that exposes an interface through a file descriptor.

这篇关于在C ++中的ifstream上设置超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆