I need to write a program that receives a block device as input, like /dev/sda1, and has to perform a set of operations depending on if the filesystem inside are currently running or not.
We'll assume the input will always has a correct linux directory tree, the only I need to know is if there's a particular directory structure or file/s that can reliably determine whether the system inside is running. I mean whether the filesystem contains the root of a system that is powered on.
It should work for any filesystem or linux kernel version.
Thanks!
Best Answer
I’ve written a function that returns
1
if the argument is the root device,0
if it is not, and a negative value for error:The first two tests are basically sanity checks: if
stat("/", …)
fails or “/
” is not a directory, your filesystem is broken. Thest_ino
tests are something of a shot in the dark. AFAIK, inode numbers should never be negative or zero. Historically (by which I mean 30 years ago), the root directory always had inode number 1. This may still be true for a few flavors of *nix (anybody heard of “Minix”?), and it may be true for the special filesystems, like/proc
, and for Windows (FAT) filesystems, but most contemporary Unix and Unix-like systems seem to use inode number 1 for tracking bad blocks, pushing the root up to inode number 2.S_ISBLK
is true for “block devices”, like/dev/sda1
, where the output fromls -l
begins with “b
”. Likewise,S_ISCHR
is true for “character devices”, where the output fromls -l
begins with “c
”. (You may occasionally see disk names like/dev/rsda1
; the “r
” stands for “raw”. Raw disk devices are sometimes used forfsck
and backup, but not mounting.) Every inode has ast_dev
, which says what filesystem that inode is on. Inodes for devices also havest_rdev
fields, which say what device they are. (The two comma-separated numbers you see in place of the file size when youls -l
a device are the two bytes ofst_rdev
.)So, the trick is to see whether the
st_rdev
of the disk device matches thest_dev
of the root directory; i.e., is the specified device the one that “/
” is on?