#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdlib.h> /*exit()*/
#define RWRWRW (S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH)
int main()
{
umask(0);
if(creat("file1",0666)<0)
{
printf("Creat file1 error.\n");
exit(1);
}
umask(0226);
if(creat("file2",0666)<0)
{
printf("Creat file2 error.\n");
exit(1);
}
return 0;
}
代码分析:
(S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH)等效于0666
因为执行(x)权限仅作用于目录,代表能否进入目录。
umask为默认值需要关掉的权限,文件权限计算公式为:mode&(~umask)
注意:在普通用户下,执行程序。
程序运行结果:
lyg@ubuntu:~/tmp$ ls -l
total 16
-rw-rw-rw- 1 lyg lyg 0 Apr 11 01:10 file1
-r--r----- 1 lyg lyg 0 Apr 11 01:10 file2
-rwxrwxr-x 1 lyg lyg 8662 Apr 11 01:10 test
-rw-rw-r-- 1 lyg lyg 423 Apr 11 01:10 test.c
file2的权限计算:
110 110 110 & (~(010 010 110))=110 110 110 & 101 101 001=100 100 000