多线程语义下的fork O_CLOEXEC close-on-exec

man 2 open
man eventfd

O_CLOEXEC (since Linux 2.6.23)
Enable the close-on-exec flag for the new file descriptor. Specifying this flag permits a program to avoid additional fcntl(2) F_SETFD
operations to set the FD_CLOEXEC flag.

          Note  that  the use of this flag is essential in some multithreaded programs, because using a separate fcntl(2) F_SETFD operation to set the
          FD_CLOEXEC flag does not suffice to avoid race conditions where one thread opens a file descriptor and attempts  to  set  its  close-on-exec
          flag  using  fcntl(2)  at  the same time as another thread does a fork(2) plus execve(2).  Depending on the order of execution, the race may
          lead to the file descriptor returned by open() being unintentionally leaked to the program executed by the child process created by fork(2).
          (This  kind  of race is in principle possible for any system call that creates a file descriptor whose close-on-exec flag should be set, and
          various other Linux system calls provide an equivalent of the O_CLOEXEC flag to deal with this problem.)

https://www.cnblogs.com/zhangxuan/p/6297617.html

man fcntl:
FD_CLOEXEC:

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.

   In multithreaded programs, using fcntl() F_SETFD to set the close-on-exec flag at the same time as another thread performs a fork(2) plus execve(2)
   is vulnerable to a race condition that may unintentionally leak the file descriptor to the program executed in the child process.  See the  discus‐
   sion of the O_CLOEXEC flag in open(2) for details and a remedy to the problem.

在线程中fork?
多线程语义下的fork
man 3 pthread_atfork

https://www.cnblogs.com/liyuan989/p/4279210.html
https://blog.codingnow.com/2011/01/fork_multi_thread.html

你可能感兴趣的:(多线程语义下的fork O_CLOEXEC close-on-exec)