I am trying to calculate and display in percentage the current disk usage with this:
use nix::sys::statvfs::statvfs;
macro_rules! cast {
($x:expr) => {
u64::from($x)
};
}
fn main() {
let stat = statvfs("/var/db".as_bytes()).unwrap();
// f_frsize
// let total_space = cast!(stat.fragment_size()) * cast!(stat.blocks());
// let avail_space = cast!(stat.fragment_size()) * cast!(stat.blocks_available());
// f_bsize
let total_space = cast!(stat.block_size()) * cast!(stat.blocks());
let avail_space = cast!(stat.block_size()) * cast!(stat.blocks_available());
let used = total_space - avail_space;
let usage = used * 100 / total_space;
println!("total: {}", total_space);
println!("avail: {}", avail_space);
println!("used: {}", used);
println!("use%: {}%", usage);
}
The output on my current test system is:
total: 6779424768
avail: 3697811456
used: 3081613312
use%: 45%
Output of df -B 1 /var/db
# df -B 1 /var/db
Filesystem 1B-blocks Used Available Use% Mounted on
/dev/loop3 6779424768 2713636864 3697811456 43% /var/db
Used
field not matching 2713636864
I am calculating it by doing 6779424768-3697811456 = 3081613312
Output of df -h /var/db
:
# df -h /var/db
Filesystem Size Used Avail Use% Mounted on
/dev/loop3 6.4G 2.6G 3.5G 43% /var/db
I think I am missing something probably converting the units, I tried already using f_frsize
instead of f_bsize
and result still the same, the code above returns 45
and df 43
.
Any ideas?