Skip to content
systemcoding.dev
Systems Programming

Redirect stdout to a File with dup2

Redirect stdout to a file in C by opening it and calling dup2 onto descriptor 1. Includes saving and restoring the terminal and the fork and exec case.

7 min read
Summarize in AI
Flat illustration of user space above the system call boundary, the kernel and the hardware, with the C, FreeBSD and Linux logos.

A shell redirection like ./report > out.txt looks like magic until you see that it is three system calls. The shell opens out.txt, makes descriptor 1 point at it, and then starts your program. The call that does the pointing is dup2(). Learning it takes ten lines of C and pays off every time you build a launcher, a logger or a test harness that has to capture another program's output. This post shows the smallest working redirect, the version that saves and restores the terminal so you can redirect temporarily, and the fork() plus exec() form that real shells use. It assumes you know that descriptor 1 is standard output; what a file descriptor is covers that from the start.

What dup2 does

dup2(oldfd, newfd) makes newfd refer to the same open file as oldfd. If newfd is already open, dup2() closes it first, and it does both steps atomically, so no other thread can slip an open() into the gap and steal the number. After a successful call, oldfd and newfd are two descriptors for one open file, and they share the file offset.

POSIX specifies the return value as newfd on success and -1 with errno set on failure. There is one special case worth memorizing: if oldfd is a valid descriptor and equals newfd, dup2() does nothing and returns newfd. That matters when you open a file and it happens to receive the number you wanted, which is exactly what occurs if descriptor 1 was closed beforehand.

The declaration lives in <unistd.h>:

c
int dup2(int oldfd, int newfd);

The smallest redirect

Open the file, dup2() it onto STDOUT_FILENO, close the original descriptor, then print as normal. Everything written to descriptor 1 from this point lands in the file:

redirect.cc
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void)
{
    int fd = open("out.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd < 0) {
        perror("open");
        return EXIT_FAILURE;
    }

    if (dup2(fd, STDOUT_FILENO) < 0) {
        perror("dup2");
        return EXIT_FAILURE;
    }
    close(fd);

    printf("this goes to out.txt\n");
    return EXIT_SUCCESS;
}

Compiled with gcc -Wall -o redirect redirect.c on GCC 14 and run, the terminal stays silent:

Text

The text is in the file instead, which you can see with cat out.txt:

Text
this goes to out.txt

Two details make this correct rather than lucky. First, close(fd) after the dup2() is safe because descriptor 1 is now an independent reference to the same open file. Closing the extra number prevents a descriptor leak without affecting the redirect. Second, printf() writes into a buffer owned by the C library. Because stdout is no longer a terminal, the library switches to full buffering and flushes when the buffer fills or the program exits. Here the normal exit from main flushes it. If your program called _exit() or crashed first, the text would be lost.

Flush before you switch

The buffering point is the most common source of "my redirect is out of order" bugs. If you write to stdout, then redirect, the earlier text can still be sitting in the stream buffer and will be written to the new destination, not the old one. Call fflush(stdout) before the dup2() when anything may be pending:

order.cc
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>

int main(void)
{
    printf("before redirect\n");
    fflush(stdout);              /* push it to the terminal now */

    int fd = open("log.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
    dup2(fd, STDOUT_FILENO);
    close(fd);

    printf("after redirect\n");
    return 0;
}

The terminal shows only the first line, and log.txt holds the second:

Text
before redirect

Remove the fflush and run it with the terminal as stdout. Standard output to a terminal is line buffered, so the first line would flush at its newline anyway; the bug appears when the first run's stdout is a pipe or file, where the stream is fully buffered. Defensive code flushes explicitly rather than depending on which case it is in.

Saving and restoring the terminal

A permanent redirect is rarely what a function wants. A test helper, for instance, redirects stdout for one call and then goes back. The trick is to keep a spare descriptor pointing at the original stdout with dup() before you overwrite it, then dup2() it back:

capture.cc
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>

static void noisy(void) { printf("from noisy()\n"); }

int main(void)
{
    fflush(stdout);
    int saved = dup(STDOUT_FILENO);          /* spare copy of the terminal */
    int fd = open("captured.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
    dup2(fd, STDOUT_FILENO);
    close(fd);

    noisy();
    fflush(stdout);                          /* land it in the file */

    dup2(saved, STDOUT_FILENO);              /* terminal is back */
    close(saved);

    printf("back on the terminal\n");
    return 0;
}

The terminal shows one line, and captured.txt contains the other:

Text
back on the terminal

Notice the second fflush(stdout). It is not optional. Without it the text from noisy() is still in the buffer when you restore the terminal, and it would be flushed there later instead of into the file. Every redirect boundary needs a flush on both sides.

How a shell launches a redirected command

A shell cannot redirect its own stdout for a child, because that would redirect the shell's output too. It forks first, changes the descriptor table in the child, and then replaces the child with the program. The child's table survives exec(), so the program starts with 1 already pointing at the file:

launch.cc
#include <fcntl.h>
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void)
{
    pid_t pid = fork();
    if (pid < 0) { perror("fork"); return 1; }

    if (pid == 0) {
        int fd = open("ls.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
        if (fd < 0) { perror("open"); _exit(127); }
        dup2(fd, STDOUT_FILENO);
        close(fd);
        execlp("ls", "ls", "-1", "/etc/hostname", (char *)NULL);
        perror("execlp");
        _exit(127);
    }

    int wstatus;
    waitpid(pid, &wstatus, 0);
    printf("child exited with %d\n", WEXITSTATUS(wstatus));
    return 0;
}

Running it prints one line, and the listing goes into ls.txt:

Text
child exited with 0

This split into fork, redirect and exec is how >, <, 2>&1 and pipelines are implemented. Redirecting standard error into the same place is one more call in the child, dup2(fd, STDERR_FILENO), which is the system-call form of 2>&1 when both numbers point at the same file.

Mistakes worth knowing

Three errors account for most failed redirects. Passing the arguments in the wrong order is the first: dup2(STDOUT_FILENO, fd) overwrites your file descriptor with the terminal and redirects nothing. The order is old first, new second, which reads as "make new a copy of old".

The second is forgetting O_TRUNC or choosing O_APPEND by accident. Without O_TRUNC, a shorter new output leaves the tail of the previous run's data in the file. With O_APPEND the writes always go to the end, which is what >> does and not what > does.

The third is redirecting in a multithreaded program. Descriptor 1 is shared by every thread, so one thread's temporary redirect also captures every other thread's printf() for its duration. If you need isolation, redirect only in a child process. When you cannot fork, open a separate stream with fopen() or fdopen() and write to it instead of touching descriptor 1.

Checking the failure paths

dup2() can fail, and the failures are informative. EBADF means oldfd is not an open descriptor or newfd is outside the range the process may use, which in practice means the earlier open() failed and you passed -1. EINTR means a signal arrived while the call was in progress; POSIX allows it, so a program that installs signal handlers without SA_RESTART should retry. EMFILE appears if newfd is at or above the RLIMIT_NOFILE limit.

A defensive version wraps the call once and reuses it everywhere:

redirect_to.cc
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>

/* Point target at path. Returns 0 on success, -1 with errno set. */
int redirect_to(int target, const char *path, int flags)
{
    int fd = open(path, flags, 0644);
    if (fd < 0)
        return -1;

    int rc;
    do {
        rc = dup2(fd, target);
    } while (rc < 0 && errno == EINTR);

    int saved = errno;
    if (fd != target)
        close(fd);
    errno = saved;
    return rc < 0 ? -1 : 0;
}

The fd != target check handles the special case from earlier: if open() returned the number you wanted, dup2() was a no-op and closing fd would close your new stdout. Preserving errno across close() keeps the original failure reason visible to the caller.

On Linux there is also dup3(oldfd, newfd, O_CLOEXEC), which does the same job and can set the close-on-exec flag on the new descriptor atomically. That matters for descriptors you do not want a later exec() to inherit, and dup3 gets its own post in this cluster.

When not to use dup2

If you only need your own output to go to a file, fprintf(file, ...) on a FILE * from fopen() is simpler and has no global effect. Reach for dup2() when something you do not control writes to descriptor 1, such as a library that prints to stdout or a program you are about to exec().

Share

Keep reading

Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.