Linux 串口 一次性read接收不定长的数据(非阻塞,非延时) 程序分析

2019-07-13 09:06发布

二话不说,直接上代码。/*********************Copyright(c)************************************************************************ ** Guangzhou ZHIYUAN electronics Co.,LTD ** ** http://www.embedtools.com ** **-------File Info--------------------------------------------------------------------------------------- ** File Name: serial-test.c ** Latest modified Data: 2008-05-19 ** Latest Version: v1.1 ** Description: NONE ** **-------------------------------------------------------------------------------------------------------- ** Create By: zhuguojun ** Create date: 2008-05-19 ** Version: v1.1 ** Descriptions: epc-8000's long time test for serial 1,2,3,4 ** **-------------------------------------------------------------------------------------------------------- *********************************************************************************************************/ #include #include #include #include #include #include #include #include #include #include #include #include #include #define DATA_LEN 0xFF /* test data's len */ //#define DEBUG 1 /********************************************************************************************************* ** Function name: openSerial ** Descriptions: open serial port at raw mod ** input paramters: iNum serial port which can be value at: 1, 2, 3, 4 ** output paramters: NONE ** Return value: file descriptor ** Create by: zhuguojun ** Create Data: 2008-05-19 **-------------------------------------------------------------------------------------------------------- ** Modified by: ** Modified date: **-------------------------------------------------------------------------------------------------------- *********************************************************************************************************/ static int openSerial(char *cSerialName) { int iFd; struct termios opt; iFd = open(cSerialName, O_RDWR|O_NOCTTY|O_NONBLOCK|O_NDELAY); if(iFd < 0) { perror(cSerialName); return -1; } tcgetattr(iFd, &opt); //cfsetispeed(&opt, B57600); //cfsetospeed(&opt, B57600); cfsetispeed(&opt, B115200); cfsetospeed(&opt, B115200); /* * raw mode */ opt.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG); opt.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON); opt.c_oflag &= ~(OPOST); opt.c_cflag &= ~(CSIZE | PARENB); opt.c_cflag |= CS8; /* * 'DATA_LEN' bytes can be read by serial */ opt.c_cc[VMIN] = DATA_LEN; opt.c_cc[VTIME] = 150; if (tcsetattr(iFd, TCSANOW, &opt)<0) { return -1; } return iFd; } //粘连的字符串最后保存在*p指向的地址所在的内存中 static int mystrcat(char *p,char *q) { int ret = -1; char *pp = p; ret = (p != NULL) && (q != NULL); if(ret) { while(*pp != '