~/ learn/ comp-325/ cards/ And that is the whole trick behind dup
1 of 10

Redirection the long way: close, then dup

Redirection the long way: close, then dup

Answer

int fd = open("out.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644); close(1); if (dup(fd) != 1) { perror("dup"); return 1; } printf("this goes into out.txt\n");

dup() takes the lowest free slot, and after close(1) that is slot 1 — so the duplicate necessarily becomes standard output. This is exactly what the shell does for the > operator.

S&K 3e ch18 §18.8.1 and ch19 §19.4.2; dup/dup2 semantics per POSIX.1-2024

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/4b7d4238-3190-4d1c-8add-ee3fe73d3329/flashcard utf-8 LF