Search code examples
clinuxpipesystem-callsstdio

Pipe stdout of system() to stdin of other system()


I want to learn how to use pipes in C, and tried to do basic things like for example cloning the behaviour of | in shell.

This is my first try:

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

#include <unistd.h>


int main(void)
{
    FILE    *stdin_tmp;

    stdin_tmp   = stdin;
    stdin       = stdout;
    system("cat /tmp/test.txt");
    system("less");
    stdin       = stdin_tmp;

    return  0;
}

This is what I want to do (written in shell):

cat /tmp/test.txt |less

The behaviour is obviously not what I expected. less isn't receiving the output of cat.

How is it done correctly?


Solution

  • Try the popen() function.

    Here's the prototype for it:

    FILE *popen(const char *command, const char *type);
    

    And here's a correct way to use it:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void)
    {
        int ch;
        FILE *input;
        FILE *output;
    
        input = popen("cat /tmp/test.txt", "r");
        output = popen("less", "w");
        if (!input || !output)
            return EXIT_FAILURE;
        while( (ch = fgetc(input)) != EOF )
            fputc(ch, output);
        pclose(input);
        pclose(output);
    
        return 0;
    }