zl程序教程

您现在的位置是:首页 >  其他

当前栏目

软件考古学: O_CLOEXEC/FD_CLOEXEC

软件 FD
2023-09-14 09:13:13 时间

概述

O_* O代表什么意思?open flag。打开标志位。O_CLOEXEC 这个意思是打开的一个标志位,在执行exec时,在新fork的程序里需要关闭此fd。

引入

https://github.com/torvalds/linux/commit/f23513e8d96cf5e6cf8d2ff0cb5dd6bbc33995e4
上面这个commit 引入了这个标志位;为了处理一个问题:在多线程的程序(更精确的说法,所有使用了带有CLONE_FILES的clone函数的程序)下存在运行先后问题:
线程 #1 线程 #2
fd=open() 线程1 打开一个文件
fork + exec // 线程而执行一个fork/exec
fcntl(fd,F_SETFD,FD_CLOEXEC) 线程1设置标志位,此时已经晚了,最终导致fork/exec出来的进程还有线程1打开的文件,可能导致敏感文件描述符泄露。

In some applications this can happen frequently. Take a web browser. One thread opens a file and another thread starts,