12

我尝试使用 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 内核上失败。

怎么了?谢谢!

4

3 回答 3

12

决定暴露O_CLOEXEC标志fcntl(fd, F_GETFL)是安全漏洞。此提交在内核 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首先依赖于可见性。

于 2013-08-19T04:05:35.213 回答
2

fcntl 调用参数F_GETFD,flag 是2.6 中出现FD_CLOEXEC的支持。. 阅读手册:O_CLOEXEC23

 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.
于 2013-08-19T03:45:57.987 回答
2

你这样做是不对的。你应该这样做:

int ret = fcntl(fd, F_GETFD);
if (ret & FD_CLOEXEC) {
...
}
于 2014-09-26T22:33:50.890 回答