第三章

    科技2022-07-10  91

    函数Umask

    #include <sys/types.h> #include <sys/stat.h> mode_t umask(mode_t cmask)

    mode_t umask(mode_t mask);//函数原型 该函数为进程设置文件模式屏蔽字,并返回以前的值。 即在创建新文件或目录时屏蔽掉你希望新文件或新目录不应有的访问权。比如说你不希望新创建的文件或目录拥有可执行的权限,那么只需将它的可执行权限作为该函数的参数,利用该函数将其屏蔽掉。 使用如下选项分别表示文件的9种访问权限。 我们可以是使用此函数来设置允许 当前进程 创建的文件或目录的最大可操作权限。 比如说,当我们在一个源程序的开始加上 umask(0) 这样一句代码。那么,在这个程序里后边所有创建的文件和目录的最大权限就被限制了。只是这里的限制相当于没有限制,因为这里的0就代表的其实就是000 000 000 ,即所有的权限都没有。也就是并没有屏蔽任何权限。那么,创建文件和目录的 最大权 限依然是0777(user、group、other都拥有读、写和可执行的权利)。

    转:https://blog.csdn.net/guaiguaihenguai/article/details/79934142

    测试程序

    #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main() { int fd = open("a",O_RDWR | O_APPEND | O_CREAT,0664); if (-1 == fd) { perror("open file"); exit(1); } umask(0222); //更改权限掩码,屏蔽写权限 close(fd); fd = open("b",O_RDWR | O_APPEND | O_CREAT,0664); if (-1 == fd) { perror("open file"); exit(1); } close(fd); return 0; }

    #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #define RWRWRW (S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH) int main(void) { umask(0); if(creat("hello", RWRWRW) < 0) { printf("creat error for hello\n"); exit(1); } umask(S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH); if(creat("world", RWRWRW) < 0) { printf("creat error for world"); exit(1); } exit(0); }

    Processed: 0.014, SQL: 8