File: chkfs.c

package info (click to toggle)
prrte 4.0.1-2
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 9,108 kB
  • sloc: ansic: 81,373; sh: 4,289; perl: 3,150; makefile: 1,878; python: 610; lex: 352
file content (86 lines) | stat: -rw-r--r-- 1,765 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#define _GNU_SOURCE
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <errno.h>
#include <mntent.h>
#include <string.h>
 #include <fcntl.h>

//#define MOUNT_FILE "/etc/mtab"
#define MOUNT_FILE "/proc/mounts"

static int mountpoint(char *filename, char **fstype)
{
    struct stat s;
    struct mntent mnt;
    FILE *fp;
    dev_t dev;
    char buf[1024];
    int fd;

    fd = open(filename, O_RDONLY);
    if (0 > fd) {
        fprintf(stderr, "CANNOT OPEN %s\n", filename);
        return EINVAL;
    }
    if (fstat(fd, &s) != 0) {
        return EINVAL;
    }
    close(fd);

    dev = s.st_dev;

    if ((fp = setmntent(MOUNT_FILE, "r")) == NULL) {
        return EINVAL;
    }

    while (getmntent_r(fp, &mnt, buf, sizeof(buf))) {
        fd = open(mnt.mnt_dir, O_RDONLY);
        if (0 > fd) {
            // probably lack permissions
            continue;
        }
        if (fstat(fd, &s) != 0) {
            close(fd);
            continue;
        }

        if (s.st_dev == dev) {
            *fstype = strdup(mnt.mnt_type);
            close(fd);
            return 0;
        }
        close(fd);
    }

    endmntent(fp);

    // Should never reach here.
    return EINVAL;
}

int main(int argc, char **argv)
{
    int n, rc;
    char *fstype;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s file1 file2 ...\n", argv[0]);
        return 1;
    }

    for (n=1; NULL != argv[n]; n++) {
        rc = mountpoint(argv[n], &fstype);
        if (0 == rc) {
            fprintf(stdout, "Return: %d File: %s FStype: %s\n", rc, argv[n], fstype);
            free(fstype);
        } else {
            fprintf(stdout, "File: %s Unknown type\n", argv[n]);
        }
    }

    return 0;
}