int main() { struct statfs sfs; struct stat statbuf; const char *path = "/"; // 查询根文件系统
printf("--- Demonstrating modern alternative to ustat: statfs ---\n");
// 方法 1: 使用 statfs 直接查询路径 printf("1. Querying filesystem info for path '%s' using statfs():\n", path); if (statfs(path, &sfs) == 0) { printf(" Filesystem Type (Magic): 0x%lx\n", (unsigned long)sfs.f_type); printf(" Block Size: %ld bytes\n", (long)sfs.f_bsize); printf(" Total Blocks: %ld\n", (long)sfs.f_blocks); printf(" Free Blocks: %ld\n", (long)sfs.f_bfree); printf(" Available Blocks: %ld (for non-root users)\n", (long)sfs.f_bavail); printf(" Total Inodes: %ld\n", (long)sfs.f_files); printf(" Free Inodes: %ld\n", (long)sfs.f_ffree); printf(" Filesystem ID: %d:%d\n", (int)sfs.f_fsid.__val[0], (int)sfs.f_fsid.__val[1]); } else { perror("statfs"); exit(EXIT_FAILURE); }
// 方法 2: 先用 stat 获取设备号,再用 statfs 查询 (模拟 ustat 的思路,但用 statfs) printf("\n2. Getting device number with stat() and querying with statfs():\n"); if (stat(path, &statbuf) == 0) { printf(" Device ID for '%s': %ld\n", path, (long)statbuf.st_dev); // 注意:没有直接的 "statfs_by_dev" 函数。 // 我们仍然需要一个路径。现代方法是直接用路径查询。 // 如果真的需要基于设备号查询,需要遍历 /proc/mounts 等找到挂载点。 // 这正是 ustat 设计上的局限性。 printf(" Note: Modern statfs works with paths, not device IDs directly.\n"); printf(" This is more robust than the old ustat approach.\n"); } else { perror("stat"); }
printf("\n--- Summary ---\n"); printf("1. ustat is obsolete and deprecated on modern Linux systems.\n"); printf("2. Use statfs() or statvfs() instead for querying filesystem information.\n"); printf("3. These modern functions provide more details and work correctly with all filesystem types.\n");
--- Demonstrating modern alternative to ustat: statfs --- 1. Querying filesystem info for path '/' using statfs(): Filesystem Type (Magic): 0xef53 Block Size: 4096 bytes Total Blocks: 123456789 Free Blocks: 56789012 Available Blocks: 50000000 (for non-root users) Total Inodes: 30000000 Free Inodes: 25000000 Filesystem ID: 12345:67890
2. Getting device number with stat() and querying with statfs(): Device ID for '/': 64768 Note: Modern statfs works with paths, not device IDs directly. This is more robust than the old ustat approach.
--- Summary --- 1. ustat is obsolete and deprecated on modern Linux systems. 2. Use statfs() or statvfs() instead for querying filesystem information. 3. These modern functions provide more details and work correctly with all filesystem types.
12. 总结
ustat 是一个历史遗留的、已被弃用的系统调用。
历史作用:在早期 Unix 系统中用于查询文件系统基本信息。
为何弃用:
功能有限且不准确。
基于设备号的设计不适用于现代复杂文件系统。
现代替代品:
statfs(path, &buf): 通过路径查询文件系统信息(推荐)。
statvfs(path, &buf): POSIX 标准接口,可移植性更好。
给 Linux 编程小白的建议:完全不需要学习 ustat。从一开始就应该学习和使用 statfs 或 statvfs 来获取文件系统信息。