mario::konrad
programming / C++ / sailing / nerd stuff
Multiprocessing: Tutorial 04
© 2002 / Mario Konrad

Introduction

Sometimes it’s useful to redirect the output (stdout for example) of a child process to the parent process. This tutorial shows how to redirect the stdout of the child process to a pipe which the parent process is reading.

Walkthrough

This walkthrough only shows the important stuff.

The pipe file descriptors have to be known to the parent as well as to the child process, therefore we’ll declare it in the global space.

static int pfd[2]; // pipe file descriptors

The child and parent codes are separated in functions. Let’s have a look at the child code first.

static void child(void)
{

We close the end of the pipe, that we never need: the reading end.

    // close reading end of pipe (not used in this process)
    close(pfd[0]);

Now we have to close stdout (file descriptor 1) and redirect it to the pipe.

    // redirect stdout to pipe
    close(1); // close stdout
    dup2(pfd[1], 1); // redirect to pipe

To demonstrate that stdout is redirected now, let’s print out some text:

    // write output
    printf("child `<%d>` to stdout", getpid());

The parent process is not very spectacular, business as usual. It defines a buffer (line 32), closes the write-end of the pipe (not used, line 38) and reads from the pipe until the other end gets closed (line 42). The output is written to stdout (line 44). Remember we only redirected it within the context of the child process. Within the context of the parent process, stdout remains unchanged.

static void parent(int pid_child)
{
#define BUFFER_SIZE (32)
    char buffer[BUFFER_SIZE+1];

    // status message
    fprintf(stderr, "parent `<%d>`: child `<%d>`\n", getpid(), pid_child);

    // close writing end of pipe (not used in this process)
    close(pfd[1]);

    // read from child (through pipe) and write it on stdout
    bzero(buffer, BUFFER_SIZE+1);
    while (read(pfd[0], &buffer, BUFFER_SIZE) > 0)
    {
        printf("`<%d>`: [%s]\n", pid_child, buffer);
        bzero(buffer, BUFFER_SIZE);
    }

    // wait for child to terminate and then terminate self
    waitpid(pid_child, 0, 0);
    fprintf(stderr, "parent `<%d>` done.\n", getpid());
    exit(0);
#undef BUFFER_SIZE
}

The function main is rather boring. Just the usual fork stuff we have seen in previous tutorials. Therefore the code is noth shown here.

Compile and Execute

Compilation and execution is very easy since you don’t need any special library.

To compile use the following command:

$ gcc -o process4 process4.c

To execute is just as easy as to compile:

$ ./process4

Downloads

All source code files provided by this page is free to copy, modify, redistribute and use for any purpose. The tutorial is copyrighted by Mario Konrad.