Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Continuous' C++ output of one executable as Input to another program

I am trying to pass the output generated by one executable as input into another. I have been able to send in one line at a time.

The problem is when I try to send in a 'sequence of lines generated in a while loop' from Program1 to be read as input by Program2. I tried piping the executables in terminal (as given below), but it fails to work.

./Program1 | ./Program2  
./Program1 |xargs ./Program2  
./Program1 > ./Program2  

I want to avoid File I/O.

Note: Platform : Linux

==================

Something along the lines of the following example

Program1 (Writing to Terminal)

int main(int argc, char *argv[])
{
    int i = 2200;
    while(1){    
        printf("%d \n", i);
        i++;
    }
}

Program2 (Reading from Terminal, the output of Program1)

int main(int argc, char *argv[])
    {   
        while(1){ 
        // Read 'i' values
        cout << "There are " << argc << " arguments:" << endl;
        // Loop through each argument and print its number and value
        for (int nArg=0; nArg < argc; nArg++)
        cout << nArg << " " << argv[nArg] << endl;
        }

        return 0;
    }
like image 817
mystique Avatar asked Jun 03 '16 01:06

mystique


1 Answers

The problem is that you are trying to read the program arguments. But when you pipe from one program to the next the output from the first program becomes the standard input (std::cin) of the second program.

Try this for program 2:

#include <string>
#include <iostream>

int main()
{
    std::string line;

    while(std::getline(std::cin, line)) // read from std::cin
    {
        // show that it arrived
        std::cout << "Line Received: " << line << '\n';
    }
}
like image 86
Galik Avatar answered Sep 30 '22 10:09

Galik