Есть пример http://www.gnu.org/software/libc/manual/html_node/Process-Creation-Example.html
Слегка модифицировал его, чтобы команда читалась из stdout родителя:
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <iostream>
/* Execute the command using this shell program. */
#define SHELL "/bin/sh"
using namespace std;
int
my_system ()
{
int status;
pid_t pid;
int p[2];
pipe(p);
pid = fork ();
if (pid == 0)
{ //Read
close(p[1]);
close(STDIN_FILENO);
/* This is the child process. Execute the shell command. */
dup2(p[0], STDIN_FILENO);
string str;
cin >> str;
execl (SHELL, SHELL, "-c", str.c_str(), NULL);
_exit (EXIT_FAILURE);
close(p[0]);
}
else if (pid < 0)
/* The fork failed. Report failure. */
status = -1;
else
{
close(p[0]);
close(STDOUT_FILENO);
dup2(p[1], STDOUT_FILENO);
// close(p[1]);
string s;
getline(cin, s);
cout << s;
close(STDOUT_FILENO);
/* This is the parent process. Wait for the child to complete. */
// if (waitpid (pid, &status, 0) != pid)
// status = -1;
}
return status;
}
int main()
{
my_system();
}
но почему-то никакого вывода не происходит.
Что я делаю не так?
UPDATE: обновил код, теперь команда для my_system достается из stdin
UPDATE 2: догадался, что надо делать flush буфера, тогда все работает. (т.е. это проблемы cout)