openatについてメモ
openat
int openat(int dirfd, const char *pathname, int flags);
int openat(int dirfd, const char *pathname, int flags, mode_t mode);
openatはディレクトリファイルディスクリプタを指定することで、そこを起点とする相対パスでファイルを指定できるopen。
ただし、pathnameが絶対パスの場合には、dirfdは無視される。
また、dirfdにAT_FDCWDが指定されている場合は、pathnameはワーキングディレクトリに対する相対パスとして解釈される。
そして、openatはopenと比較して、次のようなメリットがある。
- openatはスレッド毎にワーキングディレクトリを管理できる(マルチスレッド環境ではワーキングディレクトリは共有されるため)
- openしたいファイルのあるディレクトリのディレクトリファイルディスクリプタを指定する事で、ファイルの存在確認とファイル作成の間に意図しない処理が走ってしまうというレースコンディションを避ける事ができる。→TOUTTOU問題への回避策。
参考
https://linuxjm.osdn.jp/html/LDP_man-pages/man2/open.2.html
https://ja.wikipedia.org/wiki/Time_of_check_to_time_of_use
https://wiki.bit-hive.com/north/pg/openat%E3%82%B7%E3%82%B9%E3%83%86%E3%83%A0%E3%82%B3%E3%83%BC%E3%83%AB