简体   繁体   中英

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

For example, a sample df command output is

Filesystem    MB blocks      Free %Used    Iused %Iused Mounted on
/dev/hd4         512.00    322.96   37%     4842     7% /
/dev/hd2        4096.00    717.96   83%    68173    29% /usr
/dev/hd9var     1024.00    670.96   35%     6385     4% /var
/dev/hd3        5120.00      0.39  100%      158    10% /tmp

Now if I specify something like /tmp/dummy.txt I should be able to get /dev/hd3 or just hd3 .

EDIT : Thanks torek for the answer. But probing the /proc would become very tedious. Can anyone suggest me some system calls which can do the same internally?

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.

On Linux, use /proc/<pid>/mounts to access a list of mount points for a given pid , or /proc/self/mounts (with the literal word self ) to refer to yourself. ( cat the /proc/self/mount* files to see what they look like.)

Then, for each file system, you can do a statfs() call and compare f_fsid the f_fsid field to the result from an earlier statfs() on the path in question. Once the fsid's match, you have found the appropriate mounted file system and can use the other data from /proc/self/mounts . (However, see statfs(2) for restrictions on doing anything useful with f_fsid .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM