在Linux上使用开放系统调用创建文件时,为什么更改文件权限? [英] Why are the file permissions changed when creating a file with the open system call on Linux?

查看:86
本文介绍了在Linux上使用开放系统调用创建文件时,为什么更改文件权限?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用open系统调用创建具有完全权限(777)的文件,但是当我执行ls -l时,只能看到(755)权限.您能告诉我为什么文件权限不是777吗?

I am creating a file with full permission (777) using the open system call, but when I do ls -l I can see only permission as (755). Could you please tell why file permission is not 777?

代码

#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

int main()
{
        int fd;

        /* Creates a file with full permission*/
        fd = open("test", O_CREAT | O_RDWR | O_APPEND, 0777);

        if (fd = -1)
        {
                return -1;
        }

        close(fd);
}

输出

     $ ls -l
    -rwxr-xr-x 1 ubuntu ubuntu    0 2012-09-19 11:55 test

推荐答案

系统维护着一个叫做umask的值.它是进程的属性,就像PID(进程ID)或EUID(有效用户ID)一样.它将设置为022(八进制),表示系统应从创建的文件中删除组和其他写许可权.

There's a value maintained by the system called the umask; it is a property of the process, just like the PID (process ID) or EUID (effective user ID) is. It will be set to 022 (octal), which indicates that the system should remove the group and other write permission from files that are created.

在使用open()之前,您可以调用 umask(0); 您在open()中指定的模式将不会更改.您当然应该这样做以证明umask是问题所在.但是,通常最好让用户选择umask占主导地位–如果程序不遵守我的umask设置,我会变得很固执.我发现并验证问题后,往往不会再使用它.

You can call umask(0); before using open() so that the mode you specify in open() won't be altered. You should certainly do this to demonstrate that umask is the issue. However, it is generally best to let the user's choice of umask prevail — I for one get very stroppy if a program doesn't obey my umask setting; it tends not to be used again after I spot and verify the problem.

该外壳还具有一个(内置)命令umask,您可以使用该命令. 022值是一个明智的默认值.大多数时候,您不希望任何人都在写文件.

The shell also has a (built-in) command umask which you can use. The 022 value is a sensible default; most of the time, you do not want just anybody writing to your files.

这篇关于在Linux上使用开放系统调用创建文件时,为什么更改文件权限?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆