Olle
Olle

Reputation: 107

Why is it not possible to replace stdout with pipe output directly?

I want to pipe the output of a child process to the parent's stdout. I know there are other ways of doing this, but why can't a pipe's read-end be duplicated to stdout? Why doesn't the program print what is written to the pipes write end?

Here i have a minimal example (without any subprocesses) of what I'm trying to do. Im expecting to see test in the output when running, but the program outputs nothing.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void) {
    int fds[2];
    if(pipe(fds) == -1) {
        perror("pipe");
        exit(EXIT_FAILURE);
    }

    if(write(fds[1], "test", 5) == -1) {
        perror("write");
        exit(EXIT_FAILURE);
    }

    if(dup2(fds[0], STDOUT_FILENO) == -1) {
        perror("dup2");
        exit(EXIT_FAILURE);
    }

    return 0;
}

Upvotes: 1

Views: 575

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 224310

A pipe is two “files” that share a buffer and some locking or control semantics. When you write into the pipe, the data is put into the buffer. When you read from a pipe, the data is taken from a buffer.

There is nothing in the pipe that moves data to some output device.

If you use dup2 to duplicate the read side of the pipe into the standard output file descriptor (number 1), then all you have is the read side of the pipe on file descriptor 1. That means you can issue read operations to file descriptor 1, and the system will give your program data from the pipe.

There is nothing “special” about file descriptor 1 in this regard. Putting any file on file descriptor 1 does not cause that file to be automatically sent anywhere. The way standard output works normally is that you open a terminal or some chosen output file or other device on file descriptor 1, and then you send things to that device or file by writing to file descriptor 1. The operating system does not automatically write things to file descriptor 1; you have to issue write operations.

Upvotes: 2

Related Questions