syscalls

dup2() — Linux system interface

Atomically replace the target descriptor with a reference to the source open file description. If oldfd is valid and equals newfd, no replacement occurs; if oldfd is invalid, an existing target is left alone. With distinct descriptors the new close-on-exec flag is cleared; any error closing the previous target is not reported separately. Do not emulate this with close followed by dup in concurrent code. EBADF, EINTR and Linux-specific EBUSY are possible. Only replace a target you own or explicitly intend to redirect. Compile the complete C example in a fresh private working directory using gcc -std=c17 -Wall -Wextra -Wpedantic -Werror example.c -o example; run ./example. POSIX interface; tested on Linux/glibc only. These are libc-facing signatures, not raw architecture-specific syscall ABIs.

Formal Syntax & Structure

linux syntaxlinux
#include <unistd.h>int dup2(int oldfd, int newfd);

Parameters & Attributes

NameTypeDescription
oldfdintValid source descriptor.
newfdintTarget descriptor number to replace or allocate.

Return Value

int

newfd on success. On failure, returns -1 and sets errno.

Working Example

Example Snippetlinux
#define _DEFAULT_SOURCE#define _POSIX_C_SOURCE 200809L#include <errno.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <fcntl.h>
/* A failed check ends this short-lived demonstration. */#define CHECK(x) do { if (!(x)) { \    fprintf(stderr, "check failed at line %d: %s\n", __LINE__, #x); \    return EXIT_FAILURE; \} } while (0)
int main(void){    int q[2];    CHECK(pipe(q) == 0);    int target = open("/dev/null", O_RDONLY | O_CLOEXEC);    CHECK(target >= 0);    CHECK(dup2(-1, target) == -1 && errno == EBADF);    CHECK(fcntl(target, F_GETFD) >= 0);    CHECK(dup2(target, target) == target);    CHECK(dup2(q[0], target) == target);    CHECK(write(q[1], "z", 1) == 1);    CHECK(close(q[1]) == 0);    char b;    CHECK(read(target, &b, 1) == 1 && b == 'z');    CHECK(close(q[0]) == 0 && close(target) == 0);    puts("invalid source preserved target; replacement read z");    return EXIT_SUCCESS;}
Linux Reference