latest and greatest.
[oweals/busybox.git] / block_device.c
1 #include "internal.h"
2 #include <dirent.h>
3 #include <string.h>
4 #include <stdio.h>
5
6 const char      block_device_usage[] = "block_device mount-point";
7
8 static dev_t *my_device;
9 static char *my_device_name;
10
11 int 
12 match_mount(const struct FileInfo * i) {
13         if ( S_ISBLK(i->stat.st_mode) 
14          && (i->stat.st_rdev == *my_device)) {
15                 my_device_name=strdup(i->source);
16                 return 1;
17         } else
18                 return 0;
19 }
20
21 extern int
22 block_device_main(struct FileInfo * i, int argc, char * * argv)
23 {
24         char *device_name = block_device(argv[1],i);
25         if ( device_name == NULL )
26                 return -1;
27         printf("%s\n", device_name);
28         exit(0);
29 }
30
31 char * block_device(const char *name, struct FileInfo *i)
32 {
33         struct stat     s;
34         char *buf;
35         int dinam=0;
36
37         if ( stat(name, &s) ) return (char *) NULL;
38         if (!i) {
39           i=(struct FileInfo*)malloc(sizeof(struct FileInfo));
40           dinam = 1;
41         }
42         memset((void *)i, 0, sizeof(struct FileInfo));
43         my_device=(dev_t *)malloc(sizeof(dev_t));
44         *my_device = s.st_dev;
45         my_device_name = NULL;
46         i->source = "/dev";
47         i->stat = s;
48         i->processDirectoriesAfterTheirContents=1;
49         descend(i, match_mount);
50         if (dinam) free(i);
51         if ( my_device_name ) {
52                 buf = strdup(my_device_name);
53                 free(my_device);
54                 free(my_device_name);
55                 return buf;
56         } else {
57                 fprintf( stderr
58                 ,"Can't find special file for block device %d, %d.\n"
59                 ,(int) *my_device >> 8 & 0xff
60                 ,(int) *my_device & 0xff);
61                 free(my_device);
62                 return (char *) NULL;
63         }
64 }