如何在read()函数调用中实现超时? [英] How to implement a timeout in read() function call?
本文介绍了如何在read()函数调用中实现超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用串行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 OS.如何使用选择函数调用来实现?
I'm using Linux OS. How to implement using select function call?
推荐答案
select()需要5个参数,首先是最高的文件描述符+ 1,然后是fd_set用于读取,一个用于写入,一个用于异常.最后一个参数是struct 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 parameter 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 */
close(filedesc);
}
这篇关于如何在read()函数调用中实现超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文