这是一个linux各种读的动作,用于驱动测试
这是一个linux各种读的动作,用于驱动测试。 #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <time.h> #include <sys/select.h> #include <sys/types.h> #include <sys/ioctl.h> #include <sys/times.h> #include <string.h> #include <signal.h> #define READ_TRACK3_STATE _IOR('k', 2, int) static int fd_sig; //阻塞与非阻塞 int Read(int flag) { int fd,i,state; int count = 0; char buf[256]; memset(buf,0,sizeof(buf)); if(flag == 0) { if((fd = open("/dev/MSR_mgcd",O_RDONLY|O_NONBLOCK)) == -1) { printf("open error 1!\n"); return -1; } while(1) { count = read(fd,buf,256); if(count > 0) break; } printf("read byte size:%d\n",count); for(i = 0; i < count; i++) { printf("data:0x%x\n",buf[i]); } if(ioctl(fd,READ_TRACK3_STATE,&state) < 0) { printf("error!\n"); return -1; } printf("state:0x%x\n",state); //用于查看数据状态是否有效 这用于某些特殊地方 if((state >> 14) & 0x01) printf("right\n"); close(fd); } else { if((fd = open("/dev/MSR_mgcd",O_RDONLY)) == -1) { printf("open error 2!\n"); return -1; } count = read(fd,buf,256); for(i = 0; i < count; i++) { printf("data:0x%x\n",buf[i]); } if(ioctl(fd,READ_TRACK3_STATE,&state) < 0) { printf("error!\n"); return -1; } printf("state:0x%x\n",state); if((state >> 14) & 0x01) printf("right\n"); close(fd); } return 0; } //轮询 int Read_poll(void) { int fd,state,i; int count = 0; char buf[256]; fd_set rfds,wfds; if((fd = open("/dev/MSR_mgcd",O_RDONLY | O_NONBLOCK)) == -1) { printf("open error 3!\n"); return -1; } while(1) { FD_ZERO(&rfds); FD_ZERO(&wfds); FD_SET(fd,&rfds); FD_SET(fd,&wfds); select(fd+1,&rfds,&wfds,NULL,NULL); if(FD_ISSET(fd,&rfds)){ count = read(fd,buf,256); printf("read byte size:%d\n",count); for(i = 0; i < count; i++) { printf("data:0x%x\n",buf[i]); } if(ioctl(fd,READ_TRACK3_STATE,&state) < 0) { printf("error!\n"); return -1; } printf("state:0x%x\n",state); if((state >> 14) & 0x01) printf("right\n"); break; } else { printf("can not read!\n"); } } close(fd); return 0; } void read_handler(int num) { int i,count,state; char buf[256]; count = read(fd_sig,buf,256); printf("read byte size:%d\n",count); for(i = 0; i < count; i++) { printf("data:0x%x\n",buf[i]); } if(ioctl(fd_sig,READ_TRACK3_STATE,&state) < 0) { printf("error!\n"); return; } printf("state:0x%x\n",state); if((state >> 14) & 0x01) printf("right\n"); close(fd_sig); } //异步 int Read_fasync(void) { int sigl; int state; if((fd_sig = open("/dev/MSR_mgcd",O_RDONLY | O_NONBLOCK)) == -1) { printf("open error 3!\n"); return -1; } signal(SIGIO,read_handler); fcntl(fd_sig,F_SETOWN,getpid()); sigl= fcntl(fd_sig,F_GETFL); fcntl(fd_sig,F_SETFL,sigl | FASYNC); while(1); } int main(int argc, char *argv[]) { int n; if(argc < 2) return -1; n = atoi(argv[1]); switch(n) { case 0: Reandcard_normal(0); break; case 1: Reandcard_normal(1); break; case 2: Readcard_poll(); break; case 3: Readcard_fasync(); break; default: break; } return 0; }