Search code examples
c++linuxipc

Passing information between two seperate programs


I want to pass a value of an input variable in my program lets say#1 to another program #2 and i want #2 to print the data it got to screen, both are needed to be written in c++. The this will be on Linux.


Solution

  • In response to your comment to Roopesh Majeti's answer, here's a very simple example using environment variables:

    First program:

    // p1.cpp - set the variable
    #include <cstdlib>
    using namespace std;;    
    int main() {
        _putenv( "MYVAR=foobar" );
        system( "p2.exe" );
    }
    

    Second program:

    // p2.cpp - read the variable
    #include <cstdlib>
    #include <iostream>
    using namespace std;;
    
    int main() {
        char * p = getenv( "MYVAR" );
        if ( p == 0 ) {
            cout << "Not set" << endl;
        }
        else {
            cout << "Value: " << p << endl;
        }
    }
    

    Note:

    • there is no standard way of setting an environment variable
    • you will need to construct the name=value string from the variable contents