串口的select读:select读主要实现的功能是,在一定时间内不停地看串口有没有数据,有数据则进行读,当时间过去后还没有数据,则返回超时错误。
http://blog.163.com/ma95221%40126/blog/static/248221022011313303456/
#include <stdio.h> #include <string.h> #include <unistd.h> #include <fcntl.h> /* File control definitions */ #include <errno.h> #include <termios.h> /* POSIX terminal control definitions */ #include <time.h> int main(int argc,char **argv) { int nread,nwrite,i; int fd; fd = 0; fd_set rfds; /*打开串口*/ if((fd = open_port(fd,1)) < 0) { perror("open_port error!\n"); return ; } /*设置串口*/ if((i= set_opt(fd,115200,8,'N',1)) < 0) { perror("set_opt error!\n"); return (-1); } /*利用select函数来实现多个串口的读写*/ FD_ZERO(&rfds); FD_SET(fd,&rfds); struct timeval tv; tv.tv_sec = 24;//set the rcv wait time tv.tv_usec = 0;//100000us = 0.1s char buf[2048]; memset(buf,0,2048); //设置超时,超时就结束 while(1) { int res = select(fd+1,&rfds,NULL,NULL,&tv); switch(res) { case -1: perror("select error!\n"); break; case 0: printf("Time out\n" ); break; default: if(FD_ISSET(fd,&rfds)) { nread = read(fd,buf,sizeof(buf)); if(nread<0) printf("read err\n" ); else { printf("nread = %d,%s\n",nread,buf); memset(buf, 0 , sizeof(buf)); } } } } } /* 不设置超时 while(1) { FD_ZERO(&rfds); FD_SET(fd, &rfds); while(FD_ISSET(fd, &rfds)) { if(select(fd+1, &rfds, NULL,NULL,NULL) < 0) { perror("select error\n"); } else { while((nread = read(fd, buf, sizeof(buf))) > 0) { printf("nread = %d,%s\n",nread, buf); memset(buf, 0 , sizeof(buf)); } } } */ close(fd); return 0; }