Reputation: 305
I'm using statvfs
to have an extremely simple in-house df
command.
Other than not knowing how to get the file system device path, my main issue is that the available 1K blocks differ in my implementation and the df
output.
Here's mine:
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/x 959863856 21399352 938464504 2 /
df
's:
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/sda2 959863856 21399352 889636296 3% /
"Used" and "Available" are both in 1K-blocks units. The percentage could be due to rounding. How do I get the available space?
Here's my implementation:
int main(int argc, char *argv[]) {
struct statvfs stats;
statvfs(argv[1], &stats);
unsigned long n_1k_blocks = stats.f_blocks * stats.f_frsize / 1024;
unsigned long avail = stats.f_bfree * stats.f_frsize / 1024;
unsigned long used = n_1k_blocks - avail;
printf("%-*s\t%*lu\t%*lu\t%*lu\t%*.0f\t%s\n",
spaces, "/dev/x",
spaces, n_1k_blocks,
spaces, used,
spaces, avail,
spaces, 100 - (float)stats.f_bfree * 100.0 / stats.f_blocks,
argv[1] // e.g. " / "
);
return 0;
}
I call it as: ./a.out /
for the filesystem mounted at /
Side note: looking around, I read busybox's df source; coreutils is a bit way too complicated for me now
Upvotes: 2
Views: 694
Reputation: 4179
(938464504-889636296)/959863856 = .05
The difference in number of available blocks is 5%. This number most likely comes from the reserved blocks, i.e. standard df excludes reserved blocks from the output as they are not available for ordinary users.
For example, explanation from mkfs.ext4(8):
-m reserved-blocks-percentage Specify the percentage of the filesystem blocks reserved for the super-user. This avoids fragmentation, and allows root-owned daemons, such as syslogd(8), to continue to function correctly after non-privileged processes are prevented from writing to the filesystem. The default percentage is 5%.
EDIT: you should use f_bavail
instead of f_bfree
if you want to get the same results as standard df
utility.
Upvotes: 2