raw device I/O
Hello!
I use an USB device an raw device.The USB device file is:/dev/sda1 and I use raw command to bind it to /dev/raw/raw1:
[root@localhost zhang]# raw /dev/raw/raw1 /dev/sda1
/dev/raw/raw1: bound to major 8, minor 1
[root@localhost zhang]# raw -qa
/dev/raw/raw1: bound to major 8, minor 1
Then I use write and read system call to write to and read from the raw devices,the program is :
1#include <stdio.h>
2 #include <stdlib.h>
3 #include <fcntl.h>
4 #include <unistd.h>
5 #include <string.h>
6
7 int main(void){
8
9 char *p = "test raw devices";
10 int fd;
11 int len = strlen(p);
12 int n=0;
13 char buf[len+1];
14
15 if((fd = open("/dev/raw/raw1",O_RDWR)) == -1){
16 perror("fail to open /dev/raw/raw1\n");
17 exit(1);
18 }
19 printf("/dev/raw/raw1:%d\n",fd);
20
21 if((n=write(fd,p,len)) == -1){
22 perror("fail to write.\n");
23 exit(1);
}
25
26 printf("write done.%d chars written!\n",n);
27
28 lseek(fd,0,SEEK_SET);
29
30 n = 0;
31 if((n=read(fd,buf,len)) == -1){
32 perror("fail to read\n");
33 exit(1);
34 }
35 buf[len+1] = '\0';
36 printf("read ok,%d chars read:%s\n",n,buf);
37
38 close(fd);
39
40 return 0;
41 }
When I run this program,it gives me the message:
/dev/raw/raw1:3
fail to write.
: Invalid argument
In the 15 line if I replace "/dev/raw/raw1" by "/dev/sda1",It's OK! Why?
In addition,I write another program using fwrite and fread:
1 #include <stdio.h>
2 #include <string.h>
3
4 int main(void){
5 FILE *fp;
6 char *p = "test writing raw devices!";
7 int len = strlen(p);
8 int n=0;
9 char buf[len];
10
11 if((fp=fopen("/dev/raw/raw1","wb"))==NULL){
12 perror("fail to open\n");
13 exit(1);
14 }
15 if((n=fwrite(p,sizeof(char),len,fp)) == -1){
16 perror("fail to write\n");
17 exit(1);
18 }
19 printf("write ok,%d chars written.\n",n);
20
21 fclose(fp);
22
23 if((fp=fopen("/dev/raw/raw1","rb"))==NULL){
24 perror("fail to open\n");
25 exit(0);
26 }
27
28 n = 0;
29
30 if((n=fread(buf,sizeof(char),len,fp)) == -1){
31 perror("fail to fread raw device\n");
32 exit(1);
33 }
34 printf("%d chars read:%s\n",n,buf);
35
36 fclose(fp);
37
38 return 0;
39 }
It gives me the message:
write ok,25 chars written.
25 chars read:test raw devicesces!ices.
But it does not really write to the raw device.If I replace "/dev/raw/raw1" by "/dev/sda1",it's OK! Whatever "/dev/raw/raw1" and "/dev/sda1",fread is all OK! Why?
Thank you very much!
|