【问题标题】:linux file attributeslinux文件属性
【发布时间】:2012-04-28 10:09:10
【问题描述】:

使用 open syscall 写入和创建文件,文件没有属性。 fedora16 gcc-4.6.3

#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

int main()
{
    char *  str= "helloworld";
    int fd = open("test.db",O_WRONLY|O_CREAT|O_TRUNC|O_APPEND);

    write(fd,str,10);

    close(fd);
    return 0;
}

ll test.db

---------。 1 jiamo jiamo 14 Apr 17 11:34 test.db

虽然它不会创建具有默认文件属性的文件,例如touch test.db

umask : 0002

如果删除 O_TRUNC int fd = open("test1.db",O_WRONLY|O_CREAT|O_APPEND) 文件属性是:

----rwx---。 1 jiamo jiamo 14 Apr 17 12:29 test1.db

【问题讨论】:

  • 你的 shell 中的 umask 是什么?
  • umask 0002(我已经更新问题)

标签: linux file system-calls


【解决方案1】:

将所需的权限添加到 open() 系统调用:

int fd = open("test.db",O_WRONLY|O_CREAT|O_TRUNC|O_APPEND, 0666);

来自文档:

mode must be specified when O_CREAT is in the flags, and is ignored otherwise.
The argument mode specifies the permissions to use in case a new file is created.

【讨论】:

  • 值得描述:0666 通常是正确的第三个参数值,因为通常创建一个数据文件,其权限应该是“每个人都可以读写,减去用户的 umask 剥夺的任何权限”。对于某些应用程序,“正确”的第三个参数是 0444 或 0600 或 0400,但这些不太常见。对于少数(例如,编译的最后阶段),“正确”的第三个参数甚至是 0777。
【解决方案2】:

您需要将模式传递给open。然后它也会设置权限。 open 是一个可变参数函数,你可以向它传递更多参数

int open(const char *path, int oflag, ... );

做类似的事情

open(LOCKFILE, O_WRONLY | O_CREAT | O_EXCL,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);

检查各种权限位here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-18
    • 2016-08-24
    • 1970-01-01
    • 1970-01-01
    • 2014-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多