【问题标题】:open() doesn't set O_CLOEXEC flagopen() 没有设置 O_CLOEXEC 标志
【发布时间】:2013-08-20 19:02:55
【问题描述】:

我尝试使用 open() 设置 O_CLOEXEC 标志,但没有成功。

考虑以下微测试:

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

int main() {
  int fd = open("test.c", O_RDONLY | O_CLOEXEC);
  int ret = fcntl(fd, F_GETFL);
  if(ret & O_CLOEXEC) {
    printf("OK!\n");
  } else {
    printf("FAIL!\n");
  }
  printf("fd = %d\n", fd);
  printf("ret = %x, O_CLOEXEC = %x\n", ret, O_CLOEXEC);
  return 0;
} 

在内核版本为 2.6 的 linux 上运行时,测试成功并打印“OK!”,但在 3.8 或 3.9 内核上失败。

怎么了? 谢谢!

【问题讨论】:

  • 请注意,即使在 2.6.38 支持 O_CLOEXEC 之前,该标志也可能为真

标签: c linux kernel system-calls fcntl


【解决方案1】:

决定将O_CLOEXEC 标志暴露给fcntl(fd, F_GETFL) 是安全漏洞。 this commit 在内核 3.6-rc7 中进行了更改:

commit c6f3d81115989e274c42a852222b80d2e14ced6f
Author: Al Viro <viro@zeniv.linux.org.uk>
Date:   Sun Aug 26 11:01:04 2012 -0400

don't leak O_CLOEXEC into ->f_flags

Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>

换句话说,您不应该首先依赖O_CLOEXEC 可见。

【讨论】:

    【解决方案2】:

    fcntl调用参数F_GETFD,标志为FD_CLOEXEC,2.6.23中出现O_CLOEXEC支持。阅读手册:

     File descriptor flags
       The following commands manipulate the flags associated with a file descriptor.
       Currently,  only one such flag is defined: FD_CLOEXEC, the close-on-exec flag.
       If the FD_CLOEXEC bit is 0, the file descriptor will  remain  open  across  an
       execve(2), otherwise it will be closed.
    
       F_GETFD (void)
              Read the file descriptor flags; arg is ignored.
    
       F_SETFD (int)
              Set the file descriptor flags to the value specified by arg.
    

    【讨论】:

    • OP 说他在内核 2.6 上成功,但在 3.8/3.9 上失败
    • 在明显支持 O_CLOEXEC 的 3.8 内核上运行时测试失败。请阅读问题。
    • 这个答案是正确的,因为获得CLOEXEC 状态的正确 方法是使用F_GETFD 并测试FD_CLOEXEC,因为CLOEXEC 是应用于每个文件描述符而不是底层打开文件的标志。不过,这并不能解释为什么 F_GETFL 的 ABI 明显改变了。
    • 能否请您引用描述正确方式的规范?从手册中我看到测试完全正确
    • 不,它从来没有像这样记录。 F_GETFL 只是文件的打开标志;有人决定应该取出该位,因为它不会影响打开的文件,而只会影响文件描述符。这就是它没有被记录的原因。
    【解决方案3】:

    你做错了。你应该这样做:

    int ret = fcntl(fd, F_GETFD);
    if (ret & FD_CLOEXEC) {
    ...
    }
    

    【讨论】:

      猜你喜欢
      • 2014-04-13
      • 2020-04-28
      • 2012-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-18
      • 1970-01-01
      相关资源
      最近更新 更多