// 创建一个测试文件 fd = open(test_file, O_CREAT | O_WRONLY | O_TRUNC, 0644); if (fd != -1) { write(fd, "test", 4); close(fd); printf(" Created test file '%s'.\n", test_file); } else { perror(" Creating test file"); }
// 尝试读取文件 (应该成功,因为我们没有真正改变有效权限) fd = open(test_file, O_RDONLY); if (fd != -1) { printf(" Successfully opened '%s' for reading (as expected).\n", test_file); close(fd); } else { perror(" Opening test file for reading"); }
// 清理测试文件 if (unlink(test_file) == -1) { perror(" Deleting test file"); } else { printf(" Deleted test file '%s'.\n", test_file); }
printf("\n--- Important Notes ---\n"); printf("1. setfsuid/setfsgid primarily affect filesystem permission checks.\n"); printf("2. They do not change effective UID/GID for other operations.\n"); printf("3. Their main use is in system daemons like NFS servers.\n"); printf("4. The return value is the OLD fsid, success is verified by calling again.\n");
--- Demonstrating setfsuid and setfsgid --- Initial IDs: Real UID: 1000 Effective UID: 1000 Saved UID: 1000 Real GID: 1000 Effective GID: 1000 Saved GID: 1000 (By default, FS-UID and FS-GID equal Effective UID/GID)
--- Testing setfsuid --- Current FS-UID (queried): 1000 Attempting to set FS-UID to: 999 setfsuid(999) returned: 1000 (should be the old FS-UID: 1000) Verifying: setfsuid(999) again returned: 999 -> FS-UID was successfully set to 999.
--- Testing setfsgid --- Current FS-GID (queried): 1000 Attempting to set FS-GID to: 999 setfsgid(999) returned: 1000 (should be the old FS-GID: 1000) Verifying: setfsgid(999) again returned: 999 -> FS-GID was successfully set to 999.
--- Attempting file operation to observe behavior --- Created test file 'test_fsuid_file.txt'. Successfully opened 'test_fsuid_file.txt' for reading (as expected). Deleted test file 'test_fsuid_file.txt'.
--- Important Notes --- 1. setfsuid/setfsgid primarily affect filesystem permission checks. 2. They do not change effective UID/GID for other operations. 3. Their main use is in system daemons like NFS servers. 4. The return value is the OLD fsid, success is verified by calling again.
总结:对于 Linux 编程新手,setfsuid 和 setfsgid 是比较特殊的系统调用。它们不是日常编程中会频繁使用的。理解它们有助于理解 Linux 权限模型的细节,特别是文件系统权限检查是如何与进程的其他权限分离的。在编写需要代表不同用户执行文件操作的系统服务(如文件服务器)时,它们会很有用。在常规应用程序开发中,使用标准的 setuid/seteuid 或现代的 capabilities 通常更合适。