fs_sel = select(fd+1,&fs_read,NULL,NULL,&time);
时间: 2024-03-29 09:35:34 浏览: 15
-31, 32-34, 35-37, 38-40, 41-43, 44-46, 这一行代码是使用select函数进行等待串口上是否有数据可读,其中fd+1表示最大的文件47-50, 51-53, 54-56, 57-59, 60-62, 63-65,描述符加1,因为在select函数中需要设置文件描述符的数量,而fd是串口文件描述符,所 66-68, 69-71, 72-75, 76-78, 79-81, 82-84以需要将其加1。&fs_read是一个指向fd_set类型的指针,表示需要监视的文件描述符, 85-87, 88-90, 91-93, 94-96, 97-100, 101-集合,这里只监视串口文件描述符。NULL表示不需要监视可写文件描述符,也不需要103, 104-106, 107-109, 110-112, 113-115, 116-118, 119监视异常文件描述符。&time是一个指向timeval类型的指针,表示等待的超时时间,其中-121, 122-125, 126-128, 129-131, 132-134, 135-137, time.tv_sec表示等待的秒数,time.tv_usec表示等待的微秒数。如果select函数返回大于0的值,表示有文件描述符可读。
相关问题
fs_sel = select(fd+1,&fs_read,NULL,NULL,&time); 函数原型
int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);
其中,nfds 是需要检查的文件描述符数量加 1;readfds、writefds 和 exceptfds 分别是需要检查读、写和异常情况的文件描述符集合,如果不需要检查,就传入 NULL;timeout 是超时时间,如果不需要超时限制,就传入 NULL。函数返回值为就绪文件描述符的数量,如果超时时间到达,返回值为 0,如果出错,返回值为 -1。
int read_datas_tty(int fd, char *rcv_buf,int data_len,int mstimeout) { int len,fs_sel; fd_set fs_read; struct timeval time; memset(rcv_buf,0,sizeof(rcv_buf)); #if 1 FD_ZERO(&fs_read); FD_SET(fd,&fs_read); time.tv_sec = mstimeout/1000; time.tv_usec = (mstimeout%1000)*1000; fs_sel = select(fd+1,&fs_read,NULL,NULL,&time); if(fs_sel) { len = read(fd,rcv_buf,data_len); if(len == 0) return 0; ///printf("%s:%d recv buff[len = %d] is %s \r\n",__FUNCTION__,__LINE__,len,rcv_buf); ///print_payload(rcv_buf,len); return len; } else { //printf("failed [%s : %d]\r\n",__FUNCTION__,__LINE__); return 0; } #endif #if 0 printf("%s:%d \r\n",__FUNCTION__,__LINE__); len = read(fd,rcv_buf,data_len); if(len > 0) { printf("%s:%d recv buff[len = %d] is %s \r\n",__FUNCTION__,__LINE__,len,rcv_buf); print_payload(rcv_buf,len); return len; } else{ printf("failed [%s : %d]\r\n",__FUNCTION__,__LINE__); return 0; } #endif }
这是一个函数,函数名为read_datas_tty,它的作用是从指定的文件描述符fd中读取数据,数据长度为data_len,并且在指定的时间内等待数据到达。如果成功读取到数据,则将数据存储在rcv_buf中,返回值为实际读取的数据长度。如果在等待时间内没有读取到数据,则返回0。
该函数使用了select函数来等待数据到达,如果在指定时间内有数据到达,则执行read函数读取数据。如果select返回0,则表示在指定时间内没有数据到达,函数返回0。该函数还包含一些注释和调试代码,可以通过定义#if 1或#if 0来选择是否启用。