dup2 - Linux


Overview

dup2 is a system call used in Linux to duplicate a file descriptor. It creates a new file descriptor that shares the same underlying file or resource as an existing file descriptor.

Syntax

int dup2(int oldfd, int newfd);
  • oldfd: The file descriptor to be duplicated.
  • newfd: The new file descriptor to be created.

Options/Flags

None.

Examples

Duplicate a file descriptor to stdout:

int fd = open("myfile.txt", O_RDONLY);
dup2(fd, 1);
close(fd);

Duplicate a socket file descriptor:

int listenfd = socket(AF_INET, SOCK_STREAM, 0);
int connfd = accept(listenfd, NULL, NULL);
dup2(connfd, 0);
close(listenfd);
close(connfd);

Common Issues

Permission denied: Ensure that the calling process has sufficient permissions (e.g., write permissions) to the underlying file or resource.

Integration

Pipe data between commands using dup2:

int pipefds[2];
pipe(pipefds);
dup2(pipefds[1], 1);
execlp("ls", "ls");

Related Commands

  • dup: Duplicates a file descriptor.
  • fcntl: Manipulates file descriptor flags and locks.
  • open: Opens a file and returns a file descriptor.