如何实现在读函数调用超时? [英] How to implement a timeout in read function call?
本文介绍了如何实现在读函数调用超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用串行COM端口进行通信,我想我每次调用read函数调用的时间来实现一个超时。
I want to use serial com port for communication and I want to implement a timeout every time I call the read function call.
int filedesc = open( "dev/ttyS0", O_RDWR );
read( filedesc, buff, len );
编辑:
我使用Linux操作系统。如何使用select函数调用来实现?
I'm using Linux OS. How to implement using select function call?
推荐答案
选择()
需要5个参数,第一个最高的文件描述符+ 1,然后读一个FD_SET,一个写,一个是例外。最后放慢参数是timeval结构,用于超时。它返回-1错误,0超时或文件描述符在所设置的组数。
select() takes 5 parameters, first the highest file descriptor + 1, then a fd_set for read, one for write and one for exceptions. The last paramter is a struct timeval, used for timeout. It return -1 on error, 0 on timeout or the number of file descriptors in the sets that are set.
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/select.h>
int main(void)
{
fd_set set;
struct timeval timeout;
int rv;
char buff[100];
int len = 100;
int filedesc = open( "dev/ttyS0", O_RDWR );
FD_ZERO(&set); /* clear the set */
FD_SET(filedesc, &set); /* add our file descriptor to the set */
timeout.tv_sec = 0;
timeout.tv_usec = 10000;
rv = select(filedesc + 1, &set, NULL, NULL, &timeout);
if(rv == -1)
perror("select"); /* an error accured */
else if(rv == 0)
printf("timeout"); /* a timeout occured */
else
read( filedesc, buff, len ); /* there was data to read */
}
这篇关于如何实现在读函数调用超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文