execシステムコールは既存のファイルデスクリプタを保持する
つまり,次のプログラムは,ls
コマンドの出力を標準出力に出すのではなく,foo.txt
に書き込む.
#include <fcntl.h> #include <stdio.h> #include <unistd.h> int main(void) { close(STDOUT_FILENO); int fd = open("foo.txt", O_CREAT | O_WRONLY, 0644); if (fd != STDOUT_FILENO) { printf("fd: %d, stdout: %d\n", fd, STDOUT_FILENO); } else { execl("/bin/ls", "/bin/ls", NULL); } return 0; }
まず標準出力のファイルデスクリプタを閉じ,新たにfoo.txt
に対するファイルデスクリプタを作成する.ファイルデスクリプタ番号は,存在可能な最小の値が使用されるため,標準出力のファイルデスクリプタ番号が使用される.そしてexecl
によってls
コマンドが実行され,foo.txt
に内容が書き込まれる.
なお環境は以下の通り.
> gcc --version gcc (Gentoo 10.2.0-r5 p6) 10.2.0 Copyright (C) 2020 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. > uname -a Linux localhost 5.11.11-gentoo #1 SMP Thu Apr 1 16:10:32 JST 2021 x86_64 Intel(R) Core(TM) i9-9900K CPU @ 3.60GHz GenuineIntel GNU/Linux
また,以下の記事を参考にした.