【问题标题】:open() system call header file requirementsopen() 系统调用头文件要求
【发布时间】:2015-04-20 22:39:54
【问题描述】:

我正在使用 x86_64 GNU/Linux 和 gcc。
man -s2 open 的概要部分说:

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

int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
int creat(const char *pathname, mode_t mode);

现在,当我尝试编译以下代码 sn-p 时,gcc 不会引发警告/错误。

#include <stdio.h>
#include <fcntl.h>

int main(int argc, char **argv)
{
    int fd;

    fd = open("foo.txt", O_RDWR, 0777);
    if(fd == -1)
        perror("open");

    fd = creat("foo.txt", 0777);
    if(fd == -1)
        perror("creat");

    close(fd);
    return 0;
}

那么types.hstat.h 是可选的吗?它们在open() 的联机帮助页中有什么用途?

【问题讨论】:

  • 检查 fcntl.h -- 我假设它包括 types.hstat.h
  • 它包括&lt;bits/types.h&gt;&lt;bits/stat.h&gt;。但是我还是不明白为什么&lt;sys/types.h&gt;&lt;sys/stat.h&gt;man -s2 open里面。
  • 既然你没有说明,你是用-Wall编译的吗?如果没有,请执行此操作并检查是否有警告。

标签: c header-files system-calls manpage


【解决方案1】:

手册页作为对程序员和编译器制造商的说明。

您可能不需要将它们包含在您的系统中。但是,手册页描述了使用这些方法的可移植方式,因此无论如何您都应该包含它们。

【讨论】:

  • 无可争辩,无法验证对&lt;sys/types.h&gt;&lt;sys/stat.h&gt; 的需求是否因系统而异,因为我没有要测试的其他系统。你能给出任何一个明确需要这些标题的系统示例吗,因为我不想让这个可能可能不是
  • @rootkea:通常,事情会有所不同。正如 KlasLindbäck 所说,手册页指定了如何可移植地执行此操作,并且您应该坚持使用它(因为毕竟,如果不需要这些额外的包含,它不会花费任何成本;但是您的代码赢了'不编译,或者更糟的是,如果需要它们而你没有包含,则会调用 UB)。
猜你喜欢
  • 2015-06-02
  • 2015-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-10
  • 2012-10-21
  • 1970-01-01
  • 2020-10-21
相关资源
最近更新 更多