日期:2014-05-16 浏览次数:20643 次
#include<stdio.h> #include<stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <termios.h> #include <unistd.h> #include <pthread.h> char buf_send[8192]; char buf_recv[8192]; void* (read_usb0_thread)(void* ); void* (write_usb0_thread)(void* ); int g_iExit=0; int g_fd_usb0; int main(int argc ,char *argv[]) { struct termios options; g_fd_usb0=open("/dev/ttyUSB0",O_RDWR); printf("open file:%d\r\n",g_fd_usb0); if(g_fd_usb0<0) { printf("open file err:%d\n",g_fd_usb0); return 0; } if(tcgetattr(g_fd_usb0, &options) != 0) { printf("GetSerialAttr"); return 0; } options.c_iflag &= ~(IGNBRK|BRKINT|IGNPAR|PARMRK|INPCK|ISTRIP|INLCR|IGNCR|ICRNL|IUCLC|IXON|IXOFF|IXANY); options.c_lflag &= ~(ECHO|ECHONL|ISIG|IEXTEN|ICANON); options.c_oflag &= ~OPOST; if (tcsetattr(g_fd_usb0,TCSANOW,&options) != 0) { printf("SetSerialAttr"); return 0; } memset(buf_send,0x00,sizeof(buf_send)); memset(buf_recv,0x00,sizeof(buf_recv)); int iResult=0; pthread_t iUsb0RecvTheadID; pthread_t iUsb0SendTheadID; iResult = pthread_create(&iUsb0RecvTheadID, NULL, read_usb0_thread, NULL); if(0 !=iResult) { printf("create ttyusb0 read thread error:%d\n",iResult); return 0; } else { printf("create ttyUSB0 read thread sus,thread id:%d\n",iUsb0RecvTheadID); } iResult = pthread_create(&iUsb0SendTheadID, NULL, write_usb0_thread, NULL); if(0 !=iResult) { printf("create ttyusb0 write thread error:%d\n",iResult); return 0; } else { printf("create ttyUSB0 write thread sus,thread id:%d\n",iUsb0SendTheadID); } while (1) { if (g_iExit) { break; } usleep(500*1000); static int iCnt=0; iCnt++; if (iCnt%20==0) { printf("main running\n"); } } printf("program exits\n"); return 0; } void* (read_usb0_thread)(void* param) { int iResult=0; while (1) { if (g_iExit) { printf("exit usb0 read thread"); break; } memset(buf_recv,0x00,sizeof(buf_recv)); iResult = read(g_fd_usb0, buf_recv, sizeof(buf_recv)); // if (iResult>0) { printf("usb0-read:%s\n",buf_recv); } else { usleep(100*1000); } } return 0; } void* (write_usb0_thread)(void* param) { char *pBuf=NULL; int bPrintfMsg=0; int num=0; int iRet=0; while (1) { pBuf=fgets(buf_send,sizeof(buf_send)-1,stdin); if (NULL==pBuf) { printf("get:null,continue"); usleep(100*1000); continue; } if (strstr(pBuf,"quit") && strlen(pBuf)<=strlen("quit\r\n") ) { printf("receive quit command\n"); g_iExit=1; break; } if(NULL==strstr(pBuf,"\n")) { strcat(pBuf,"\n"); }