Redirecting stdout to a pipe
What you'll learn: How to use dup2() to force a program's standard output into a pipe so another process can read it.
The "Plumbing" Problem
By default, when a program calls printf(), the data flows to the "Standard Output" (stdout), which is usually your terminal screen. In systems programming, we often want to take that stream of data and reroute it—like a plumber changing the direction of a pipe—so that it flows into another process instead of onto the screen.
To do this, we use a system call called dup2(). Think of dup2() as a "clone and replace" tool. It takes an existing file descriptor (like the write-end of a pipe) and copies it onto another one (like stdout), effectively overwriting the original destination.
Using dup2() to Reroute
When we create a pipe using pipe(fd), we get two file descriptors: fd[0] for reading and fd[1] for writing. To redirect stdout, we tell the system: "Take the behavior of fd[1] and copy it over to the file descriptor for stdout (which is constant 1)."
Once this happens, the process no longer knows it’s talking to a pipe. It thinks it is still printing to the screen, but the kernel secretly sends every byte into the pipe's buffer.
A Concrete Example
Here is how you set up a child process to send its output to a pipe instead of the terminal:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main() {
int pipe_fds[2];
pipe(pipe_fds); // Create the pipe
if (fork() == 0) {
// --- CHILD PROCESS ---
// 1. Close the read end (we aren't using it)
close(pipe_fds[0]);
// 2. Redirect stdout (1) to the pipe's write end (pipe_fds[1])
// dup2(source, destination)
dup2(pipe_fds[1], STDOUT_FILENO);
// 3. Close the original pipe descriptor (it's now cloned to stdout)
close(pipe_fds[1]);
// 4. This message now goes into the pipe, NOT the screen!
printf("Hello from the redirected child!");
exit(0);
}
// Parent would read from pipe_fds[0] here...
return 0;
}
Why This Matters
This is exactly how the shell handles the "pipe" character (|). When you run ls | grep, the shell forks a process for ls and uses dup2 to point its stdout to a pipe. Simultaneously, it forks grep and points its stdin to the other end of that same pipe. The programs don't need special code to talk to each other; they just use their standard inputs and outputs, unaware that the "plumbing" has been swapped behind the scenes.
Key takeaway
Use dup2(pipe_fd, STDOUT_FILENO) to hijack a process's standard output and redirect it into a pipe.