open()无法正确设置文件权限 [英] open() not setting file permissions correctly
问题描述
我使用以下代码创建文件:
I create a file using the code below:
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
const char* filename = "./test.out";
int fd;
if(-1 == (fd = open(filename, O_CREAT|O_RDWR, 0666)))
{
perror("Error");
errno = 0;
}
else
puts("File opened");
if(-1 == (close(fd)))
{
perror("Error");
errno = 0;
}
else
puts("File closed");
return 0;
}
我将mode
参数指定为0666
,该参数应授予所有人读写权限.但是,ls -l
显示
I specify the mode
argument as 0666
, which should grant read,write access to everyone. However, an ls -l
shows
-rw-r--r-- 1 kmehta users 0 2012-01-29 16:29 test.out
如您所见,写入权限仅授予文件所有者.我不知道为什么其他所有人都没有被正确授予权限.尽管chmod a+w test.out
可以正确设置权限.
As you can see, write permissions are only granted to the owner of the file. I do not know why everyone else is not granted permissions correctly. chmod a+w test.out
sets the permissions correctly though.
代码编译为gcc -Wall test.c
规格:Opensuse 11.3 64位上的gcc v 4.5.0
Specs: gcc v 4.5.0 on Opensuse 11.3 64 bit
推荐答案
open
的mode
参数指定最大允许的权限.然后将umask
设置应用于进一步限制权限.
The mode
argument to open
specifies the maximum allowed permissions. The umask
setting is then applied to further restrict the permissions.
如果您需要将权限设置为0666,则在打开成功后,需要在文件句柄上使用fchmod
,或者在打开之前使用umask
设置进程的权限掩码.
If you need to make the permissions be 0666 specifically you will need to use fchmod
on the file handle after the open succeeds or use umask
to set the process’ permissions mask before the open.
这篇关于open()无法正确设置文件权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!