4 Copy a device or file specified as argument to /dev/ram
13 #include <sys/ioctl.h>
15 #define RAM "/dev/ram"
19 static unsigned long size_device(int fd
);
21 int main(int argc
, char *argv
[])
23 unsigned long off
, size
;
29 fprintf(stderr
, "Usage: loadramdisk <file>\n");
33 fd
= open(src
, O_RDONLY
);
36 fprintf(stderr
, "Unable to open '%s': %s\n",
37 src
, strerror(errno
));
41 /* Get the size of the device */
43 size
= size_device(fd
);
46 fprintf(stderr
, "Lseek(end) failed on '%s': %s\n",
47 src
, strerror(errno
));
50 if (lseek(fd
, 0, SEEK_SET
) != 0)
52 fprintf(stderr
, "Lseek(0) failed on '%s': %s\n",
53 src
, strerror(errno
));
57 ramfd
= open(RAM
, O_RDWR
);
60 fprintf(stderr
, "Unable to open '%s': %s\n",
61 RAM
, strerror(errno
));
64 r
= ioctl(ramfd
, MIOCRAMSIZE
, &size
);
67 fprintf(stderr
, "MIOCRAMSIZE %lu failed on '%s': %s\n",
68 size
, RAM
, strerror(errno
));
75 r
= read(fd
, buf
, sizeof(buf
));
78 fprintf(stderr
, "error reading '%s': %s\n",
79 src
, r
== 0 ? "unexpected EOF" :
83 s
= write(ramfd
, buf
, r
);
86 fprintf(stderr
, "error writing to '%s': %s\n",
87 s
>= 0 ? "short write" : strerror(errno
));
95 static unsigned long size_device(int fd
)
99 unsigned long low
, mid
, high
;
101 /* Try to find the size of a device using binary search */
105 while (mid
= low
+(high
-low
)/2, mid
> low
)
107 if (lseek(fd
, mid
, SEEK_SET
) != mid
)
109 fprintf(stderr
, "lseek to %lu failed: %s\n",
110 mid
, strerror(errno
));
116 fprintf(stderr
, "read failed at position %lu: %s\n",
117 mid
, strerror(errno
));