這是一個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;
}