// 7. 恢复原始 umask printf("\n--- Restoring original umask ---\n"); umask(old_mask); printf("Restored umask to: %03o\n", old_mask);
printf("\n--- Summary ---\n"); printf("1. umask acts as a filter on default permissions (666 for files, 777 for dirs).\n"); printf("2. Bits set to 1 in umask REMOVE the corresponding permission.\n"); printf("3. umask 022: Owner has full access, Group/Others have read/execute (not write).\n"); printf("4. umask 077: Only Owner has access (very private).\n"); printf("5. umask 002: Owner/Group have full access, Others lack write (collaborative).\n"); printf("6. The umask set in a program affects files/dirs it creates.\n");
--- Creating files/dirs with initial umask --- Permissions for 'file_with_initial_umask.txt': rw-r--r-- (644) Permissions for 'dir_with_initial_umask': rwxr-xr-x (755)
--- Changing umask to 077 --- Old umask was: 022 New umask is: 077 Permissions for 'file_with_umask_077.txt': rw------- (600) Permissions for 'dir_with_umask_077': rwx------ (700)
--- Changing umask to 002 --- Old umask was: 077 New umask is: 002 Permissions for 'file_with_umask_002.txt': rw-rw-r-- (664) Permissions for 'dir_with_umask_002': rwxrwxr-x (775)
--- Restoring original umask --- Restored umask to: 002
--- Summary --- 1. umask acts as a filter on default permissions (666 for files, 777 for dirs). 2. Bits set to 1 in umask REMOVE the corresponding permission. 3. umask 022: Owner has full access, Group/Others have read/execute (not write). 4. umask 077: Only Owner has access (very private). 5. umask 002: Owner/Group have full access, Others lack write (collaborative). 6. The umask set in a program affects files/dirs it creates.
11. 在 Shell 中使用 umask 命令
你也可以直接在终端中使用 umask 命令:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# 查看当前 umask umask
# 设置 umask 为 077 umask 077
# 创建一个文件测试权限 touch test_file_umask_077.txt ls -l test_file_umask_077.txt # 输出类似:-rw------- 1 user user 0 date time test_file_umask_077.txt
# 恢复为常见的 022 umask 022 touch test_file_umask_022.txt ls -l test_file_umask_022.txt # 输出类似:-rw-r--r-- 1 user user 0 date time test_file_umask_022.txt
12. 总结
umask() 函数(以及 umask shell 命令)是 Linux 系统中控制新建文件和目录默认权限的重要工具。