60 lines
1.4 KiB
C
60 lines
1.4 KiB
C
|
#include <stdio.h>
|
||
|
#include <stdlib.h>
|
||
|
#include <string.h>
|
||
|
#include <mntent.h>
|
||
|
#include <sys/statvfs.h>
|
||
|
|
||
|
// 获取指定路径的磁盘使用率
|
||
|
int get_disk_usage(const char *path, double *usage) {
|
||
|
struct statvfs stat;
|
||
|
|
||
|
if (statvfs(path, &stat) != 0) {
|
||
|
// 处理错误
|
||
|
perror("statvfs failed");
|
||
|
return -1;
|
||
|
}
|
||
|
|
||
|
// 计算磁盘使用率
|
||
|
unsigned long total_blocks = stat.f_blocks;
|
||
|
unsigned long free_blocks = stat.f_bfree;
|
||
|
unsigned long used_blocks = total_blocks - free_blocks;
|
||
|
|
||
|
*usage = (double)used_blocks / total_blocks * 100;
|
||
|
return 0;
|
||
|
}
|
||
|
|
||
|
int disk_usage() {
|
||
|
FILE *mounts;
|
||
|
struct mntent *ent;
|
||
|
|
||
|
mounts = setmntent("/etc/mtab", "r");
|
||
|
if (mounts == NULL) {
|
||
|
perror("setmntent failed");
|
||
|
return 1;
|
||
|
}
|
||
|
|
||
|
while ((ent = getmntent(mounts)) != NULL)
|
||
|
{
|
||
|
double usage = 0;
|
||
|
if (strstr(ent->mnt_fsname, "/dev/") != NULL)
|
||
|
{
|
||
|
//printf("%s %s %s\n", ent->mnt_fsname, ent->mnt_dir, ent->mnt_type);
|
||
|
|
||
|
if (get_disk_usage(ent->mnt_dir, &usage) != 0) {
|
||
|
fprintf(stderr, "Failed to get disk usage for %s\n", ent->mnt_dir);
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
int threshold = 1;
|
||
|
if (usage > threshold) {
|
||
|
printf("挂载点: %s 使用率: %.2f%% 阀值: %d%%\n", ent->mnt_dir, usage, threshold);
|
||
|
|
||
|
}
|
||
|
}
|
||
|
|
||
|
}
|
||
|
|
||
|
endmntent(mounts);
|
||
|
return 0;
|
||
|
}
|