tsaarni / cpp-subprocess

popen() -like C++ library with iostream support for stdio forwarding
MIT License
88 stars 21 forks source link

Is it possible to write / read to / from the child process multiple times ? #8

Closed TheFGFSEagle closed 1 year ago

TheFGFSEagle commented 1 year ago

fgelev takes the name, latitude and longitude of points on earth as input, separated by spaces, one point per line, and prints the name and elevation of the point to the stdout, one point per line, in real time (so you enter one point on the stdin and immediately get the response on the stdout, then you can enter the next point). I was trying to use your header to do this with the following code:

#include <fstream>
#include <subprocess.hpp>

int
main(int argc, char *argv[])
{
    subprocess::popen sort_cmd("fgelev", {});

    sort_cmd.stdin() << "a 0 0" << std::endl;
    sort_cmd.stdin().flush();
    std::cout << sort_cmd.stdout().rdbuf();
    sort_cmd.stdin() << "a 0 0" << std::endl;
    sort_cmd.stdin().flush();
    std::cout << sort_cmd.stdout().rdbuf();

    return 0;
}

but it hangs after the first point. Am I doing something wrong, or does your code just not support this ?

tsaarni commented 1 year ago

I think one must read without blocking, something like:

int
main(int argc, char *argv[])
{
    std::string buf;

    subprocess::popen cat_cmd("cat", {});

    cat_cmd.stdin() << "a" << std::endl;
    std::getline(cat_cmd.stdout(), buf);
    std::cout << buf << std::endl;

    cat_cmd.stdin() << "b" << std::endl;
    std::getline(cat_cmd.stdout(), buf);
    std::cout << buf << std::endl;

    cat_cmd.stdin() << "c" << std::endl;
    std::getline(cat_cmd.stdout(), buf);
    std::cout << buf << std::endl;

    return 0;
}

For simplicity, here I'm assuming there is always just one line to read after each write.

$ g++ -Wall -o test test.cpp && ./test
a
b
c
TheFGFSEagle commented 1 year ago

In fact, there is only one line - thanks, this works perfectly - I think it would be a good idea to include this as an example in the README ! :)

tsaarni commented 1 year ago

Great to hear it worked for you @TheFGFSEagle! :smile: I added that as an example to the README https://github.com/tsaarni/cpp-subprocess/commit/8a3a9084b95591786c0a7e132ee55624b719b8fd.

TheFGFSEagle commented 1 year ago

Thanks ! :)