2017-08-31 2 views
3

Je suis en train de jouer avec la bibliothèque de processus boost. Mais pour certaines raisons, je ne parviens pas à envoyer quelque chose à stdin:Écrire dans stdin d'un processus enfant

#include <iostream> 
#include <boost/process.hpp> 
using namespace boost::process; 

int main(int argc, char** argv) { 
    boost::asio::io_service ios; 

    std::future<std::string> outdata; 
    std::future<std::string> errdata; 

    child c("/usr/bin/cat", 
      std_out > outdata, 
      std_err > errdata, 
      std_in < "hi, there!", ios); 

    ios.run(); 
    std::cout << "stdout: " << outdata.get() << std::endl; 
    std::cerr << "stderr: " << errdata.get() << std::endl; 
} 

Je me attends que cela fonctionne essentiellement comme

echo "hi, there" | cat 

Mais la sortie est vide. Qu'est-ce que je rate?

Répondre

1
std_in < "hi, there!" 

Ouvre un fichier nommé "hi, there!" et l'envoie à l'enfant stdin.

Comparez: Live On Coliru

#include <iostream> 
#include <boost/process.hpp> 
using namespace boost::process; 

int main() { 
    boost::asio::io_service ios; 

    std::future<std::string> outdata; 
    std::future<std::string> errdata; 

    child c("/bin/cat", 
      std_out > outdata, 
      std_err > errdata, 
      std_in < "main.cpp", ios); 

    ios.run(); 
    std::cout << "stdout: " << outdata.get() << std::endl; 
    std::cerr << "stderr: " << errdata.get() << std::endl; 
} 

Imprime son propre code source. Voir aussi l'utilisation de boost::process::buffer: (?)

Live On Coliru

Vous devez apparemment pour vous assurer que stdin est fermé AFTE envoyer le tampon

#include <iostream> 
#include <boost/process.hpp> 
#include <boost/process/async.hpp> 
using namespace boost::process; 

int main() { 
    boost::asio::io_service ios; 

    std::future<std::string> outdata; 
    std::future<std::string> errdata; 

    async_pipe in(ios); 
    child c("/bin/cat", 
      std_out > outdata, 
      std_err > errdata, 
      std_in < in, ios); 

    std::string greeting("hi, there!"); 
    boost::asio::async_write(in, buffer(greeting), [&](boost::system::error_code, size_t) { 
       in.close(); 
      }); 

    ios.run(); 
    std::cout << "stdout: '" << outdata.get() << "'\n"; 
    std::cerr << "stderr: '" << errdata.get() << "'\n"; 
} 

Prints

stdout: 'hi, there!' 
stderr: '' 
+0

Merci. Il est là dans le document de l'API, mais j'ai réussi à l'interpréter complètement ... – choeger