#include <unistd.h> int dup(int oldfd); int dup2(int oldfd, int newfd); #define _GNU_SOURCE /* See feature_test_macros(7) */ #include <fcntl.h> /* Definition of O_* constants */ #include <unistd.h> int dup3(int oldfd, int newfd, int flags);
After a successful return, the old and new file descriptors may be used interchangeably. Since the two file descriptors refer to the same open file description, they share file offset and file status flags; for example, if the file offset is modified by using lseek(2) on one of the file descriptors, the offset is also changed for the other file descriptor.
2つのファイルディスクリプターはファイルディスクリプターフラグ (close-on-exec flag) を共有しない。複製されたディスクリプターの close-on-exec flag (fcntl(2) 参照) は off となる。
If the file descriptor newfd was previously open, it is closed before being reused; the close is performed silently (i.e., any errors during the close are not reported by dup2()).
ファイルディスクリプター newfd をクローズして再利用する処理は アトミック(不可分)に実行される。これは重要な点である。 なぜなら、 等価な機能を close(2) と dup() を使って実装しようとすると、 2 つの処理の間に newfd が再利用されてしまうという、 競合状態にさらされることになるからだ。 このような再利用が起こるのは、 メインプログラムがファイルディスクリプターを割り当てる シグナルハンドラーにより割り込まれたり、並行動作するスレッドが ファイルディスクリプターを割り当てたりすることがあるからだ。
以下の点について注意すること:
If newfd was open, any errors that would have been reported at close(2) time are lost. If this is of concern, then---unless the program is single-threaded and does not allocate file descriptors in signal handlers---the correct approach is not to close newfd before calling dup2(), because of the race condition described above. Instead, code something like the following could be used:
/* Obtain a duplicate of 'newfd' that can subsequently
be used to check for close() errors; an EBADF error
means that 'newfd' was not open. */
tmpfd = dup(newfd);
if (tmpfd == -1 && errno != EBADF) {
/* Handle unexpected dup() error. */
}
/* Atomically duplicate 'oldfd' on 'newfd'. */
if (dup2(oldfd, newfd) == -1) {
/* Handle dup2() error. */
}
/* Now check for close() errors on the file originally
referred to by 'newfd'. */
if (tmpfd != -1) {
if (close(tmpfd) == -1) {
/* Handle errors from close. */
}
}