dup、 dup2 和dup3


简介


#include <unistd.h>
int dup(int oldfd);
int dup2(int oldfd, int newfd);
int dup3(int oldfd, int newfd, int flags); // 是GNU的扩展,不一定所有系统都支持

// 这些系统调用都返回oldfd的文件描述符的副本
These system calls create a copy of the file descriptor oldfd.

// 新的文件描述符使用未用的最小的文件描述符
dup() uses the lowest-numbered unused descriptor for the new descriptor.

// dup2 系统调用同dup()大致相同,不同点是他创建的新的文件描述符使用newfd,如果原先newfd
// 打开了,在使用它之前,会先默默的关闭,然后再使用
dup2() makes newfd be the copy of oldfd, closing newfd first if necessary, but note the following:
// 如果oldfd不是有效的文件描述符,调用失败,newfd不会被关闭
If oldfd is not a valid file descriptor, then the call fails, and newfd is not closed.
// 如果oldfd有效但是和newfd是相同的值,dup2不做任何事情,返回值是newfd
If oldfd is a valid file descriptor, and newfd has the same value as oldfd, then dup2() does nothing, and returns newfd.
// 返回成功,新旧文件描述符可以交替使用
After a successful return from one of these system calls, the old and new file descriptors may be used interchangeably. They refer to the same open file description (see open(2)) and thus share file
offset and file status flags; for example, if the file offset is modified by using lseek(2) on one of the descriptors, the offset is also changed for the other.
The two descriptors do not share file descriptor flags (the close-on-exec flag). The close-on-exec flag (FD_CLOEXEC; see fcntl(2)) for the duplicate descriptor is off.

dup3() is the same as dup2(), except that:
// 调用者可以通过指定flags为O_CLOEXEC强制置位新文件描述符的 close-on-exec 标志

  • The caller can force the close-on-exec flag to be set for the new file descriptor by specifying O_CLOEXEC in flags. See the description of the same flag in open(2) for reasons why this may be useful.
    // 如果oldfd==newfd,dup3()调用失败,错误是EINVAL
  • If oldfd equals newfd, then dup3() fails with the error EINVAL

使用举例

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#define file_name "dup_test_file"
int main(int argc, char *argv[])
{
    //先调用dup将标准输出拷贝一份,指向真正的标准输出
    int stdout_copy_fd = dup(STDOUT_FILENO);
    int file_fd = open(file_name, O_RDWR);
    //让标准输出指向文件
    dup2(file_fd, STDOUT_FILENO);
    printf("hello\n");
    //刷新缓冲区
    fflush(stdout);
    //恢复标准输出
    dup2(stdout_copy_fd, STDOUT_FILENO);
    printf("world\n");
    return 0;
}

注: dup和dup2用法小结

dup, dup2, dup3