#include <stdio.h> #include <string.h> #include <malloc.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <termios.h> #include <sys/ioctl.h>//这个头文件不加 可能导致FIONREAD未定义 #define max_buffer_size 200 int fd; int flag_close; int open_serial(int k) { if(k==0) { fd=open("/dev/ttyS0",O_RDWR|O_NOCTTY); perror("open /dev/2"); } else { fd=open("dev/pts/3",O_RDWR|O_NOCTTY); perror("open /dev/pts/3"); } if(fd == -1) return -1; else return 0; } int main(int argc, char *argv[]) { char hd[max_buffer_size],*rbuf; int flag_close, retv, i, ncount=0; struct termios option; int realdata=0; int qstatus=0; open_serial(0); tcgetattr(fd,&option); cfmakeraw(&option); cfsetispeed(&option,B9600); cfsetospeed(&option,B9600); tcsetattr(fd,TCSANOW,&option); while(1) { rbuf=hd; ncount=0; printf("ready for receiving data.../n"); // while(ncount!=99) // { while(qstatus<99) ioctl(fd,FIONREAD,&qstatus);//读取串行端口缓冲区中的字节数 retv=read(fd,rbuf,200); // ncount++; // rbuf++; if(retv==-1) { perror("read"); } // } else { printf("we have received %d data/n/n",retv); printf("The data receive is :/n"); for(i=0;i<retv;i++) { printf("%d",hd[i]); } printf("/n"); } } flag_close = close(fd); if(flag_close == -1) printf("Close the Device failur!/n"); return 0 ; }