syscalls

dup() — Linux system interface

Allocate the lowest available descriptor pointing to the same open file description. File offsets and status flags are shared, descriptor flags are separate; the new descriptor has close-on-exec cleared. This is not a new independent file open. Consider F_DUPFD_CLOEXEC or dup3 where an atomic close-on-exec operation is required. EBADF and EMFILE are common failures. Each successfully allocated descriptor must be closed independently. 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 dup(int oldfd);

Parameters & Attributes

NameTypeDescription
oldfdintValid source descriptor.

Return Value

int

New nonnegative descriptor. 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){    char path[] = "sample-XXXXXX";    int f = mkstemp(path);    CHECK(f >= 0);    CHECK(unlink(path) == 0);    CHECK(write(f, "ab", 2) == 2);    CHECK(lseek(f, 0, SEEK_SET) == 0);    CHECK(fcntl(f, F_SETFD, FD_CLOEXEC) == 0);    int g = dup(f);    CHECK(g >= 0 && g != f);    int flags = fcntl(g, F_GETFD);    CHECK(flags >= 0 && !(flags & FD_CLOEXEC));    char a, b;    CHECK(read(f, &a, 1) == 1 && read(g, &b, 1) == 1);    CHECK(a == 'a' && b == 'b');    CHECK(close(f) == 0 && close(g) == 0);    printf("shared offset: %c then %c; new CLOEXEC clear\n", a, b);    return EXIT_SUCCESS;}
Linux Reference