#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <iostream>
#include <istream>
#include "boost/fdstream.hpp"

// for FILE, popen(), pclose():
#include <stdio.h>

void popen_test (std::string const& command)
{
  pid_t pid;	
  int pipeout[2];

  if (pipe(pipeout))   {
    fprintf (stderr, "Pipe failed.\n");
  }

  // Create the child process
  pid = fork ();
  if (pid == (pid_t) 0) {
    std::cout << "redirecting openout\n";
      // Redirect child stdout to pipeout[1]
      close(STDOUT_FILENO);
      dup2(pipeout[1], STDOUT_FILENO);
      close(pipeout[0]);
      close(pipeout[1]);
      setlinebuf(stdout);
    execlp("/bin/sh", "/bin/sh", "-c", command.c_str(), NULL);
  }
  else if (pid < (pid_t) 0) {
    exit(-1);
    // The fork failed.
  }

  close(pipeout[1]);
  std::istream* in = new boost::fdistream(pipeout[0]);

  // print all characters with indent
  std::cerr << "output of " << command << ":\n";
  std::string s;
  getline(*in,s);
  std::cerr << "output: " << s << std::endl;
  delete(in);
  std::cerr << "The end!\n";
}


int main()
{
    popen_test("echo coucou");
}
