Where Is a File Mounted

Where is a file mounted?

This is what I've come up with. It turns out there's usually no need to iterate through the parent directories. All you have to do is get the file's device number and then find the corresponding mount entry with the same device number.

struct mntent *mountpoint(char *filename, struct mntent *mnt, char *buf, size_t buflen)
{
struct stat s;
FILE * fp;
dev_t dev;

if (stat(filename, &s) != 0) {
return NULL;
}

dev = s.st_dev;

if ((fp = setmntent("/proc/mounts", "r")) == NULL) {
return NULL;
}

while (getmntent_r(fp, mnt, buf, buflen)) {
if (stat(mnt->mnt_dir, &s) != 0) {
continue;
}

if (s.st_dev == dev) {
endmntent(fp);
return mnt;
}
}

endmntent(fp);

// Should never reach here.
errno = EINVAL;
return NULL;
}

Thanks to @RichardPennington for the heads up on realpath(), and on comparing device numbers instead of inode numbers.

How to find out mount/partition a directory or file is on? (Linux Server)

df -P file/goes/here | tail -1 | cut -d' ' -f 1

Given the directory name, how to find the Filesystem on which it resides in C?

df `pwd`

...Super simple, works, and also tells you how much space is there...

[stackuser@rhel62 ~]$ pwd
/home/stackuser
[stackuser@rhel62 ~]$ df `pwd`
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/sda7 250056240 196130640 41223408 83% /
[stackuser@rhel62 ~]$ cd isos
[stackuser@rhel62 isos]$ pwd
/home/stackuser/isos
[stackuser@rhel62 isos]$ df `pwd`
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/sda5 103216920 90417960 11750704 89% /mnt/sda5
[stackuser@rhel62 isos]$ df $(pwd)
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/sda5 103216920 90417960 11750704 89% /mnt/sda5

...which is the likely cause of the mount point query in the first place.

Note those are backticks, and the alternate (modern) method, providing further control over slashes and expansion is df $(pwd). Tested and traverses symlinks correctly on bash, dash, busybox, zsh. Note that tcsh won't like the $(...), so stick to the older backtick style in csh-variants.

There are also extra switches in pwd and df for further enjoyment.



Related Topics



Leave a reply



Submit