How to get a device/partition name of a file ?

2020-04-13 20:38发布

问题:

I have partition structure like :

$ df
Filesystem     1K-blocks     Used Available Use% Mounted on
/dev/sda6       51606140 16939248  34142692  34% /
/dev/sda5         495844    72969    397275  16% /boot
/dev/sda7      113022648 57515608  49765728  50% /home
/dev/sda8     113022648 57515608  49765728  4% /mnt

while parsing directories content using readdir() - how to find out which file resides on what device?

readdir() invoked from root directory and parses the file name and prints its size. like from device : /dev/sda6 and list the filenames under that partition. When it reads contents from /home - it should display reading content from /dev/sda7 and list filenames

Please let me know,if you need more details/info

回答1:

There is a st_dev member in struct stat, it should uniquely identify one partition.

Example in bash:

stat ~/.vimrc
  File: `/home2//leonard/.vimrc' -> `local-priv/vimrc'
  Size: 16              Blocks: 0          IO Block: 4096   symbolic link
Device: 802h/2050d      Inode: 6818899     Links: 1
Access: (0777/lrwxrwxrwx)  Uid: ( 1024/ leonard)   Gid: ( 1024/ leonard)
Access: 2012-06-22 16:36:45.341371003 +0300
Modify: 2012-06-22 16:36:45.341371003 +0300
Change: 2012-06-22 16:36:45.341371003 +0300

The stat utility does no additional magic. Here is strace -vvv output:

lstat64("/home2//leonard/.vimrc", {st_dev=makedev(8, 2), st_ino=6818899, st_mode=S_IFLNK|0777, st_nlink=1, st_uid=1024, st_gid=1024, st_blksize=4096, st_blocks=0, st_size=16, st_atime=2012/06/22-16:36:45, st_mtime=2012/06/22-16:36:45, st_ctime=2012/06/22-16:36:45}) = 0

0x0802 is major 8(sd) partition 2, so /dev/sda2

In order to map this to actual partitions you can iterate /proc/mounts and stat all the devices (first column). The contents of /proc/mounts is just like the output of mount(1) except it comes directly from the kernel. Some distros symlink /etc/mtab to /proc/mounts.

Or you can parse /proc/partitions:

$ cat /proc/partitions
major minor  #blocks  name

   8        0  976762584 sda
   8        1    3998720 sda1
   8        2  972762112 sda2

Of course /dev/sda might not actually exist, the device could be using a long udev name like /dev/disk/by-uuid/c4181217-a753-4cf3-b61d-190ee3981a3f. Major/Minor numbers should be a reliable unique identifier of a partition.



回答2:

you can just do

df <file_name>

that will give you the device and partition for the particuar file