Answer the question
In order to leave comments, you need to log in
Emulate user input and read output from a program (pipe, C++)?
Greetings.
I need to run a third party console program that reads user input via std::cin and then returns the result to be parsed. I understand that in * nix this is done through pipes. Can you please tell me how this can be done at all?
int fd[2];
pipe(fd);
pid_t pid_fork = fork();
if(!pid_fork)
{
// Дочерний процесс
}
else
{
// Родительский процесс
}
execl("/bin/sh", "sh", "-c", "../sample/main", NULL);
Answer the question
In order to leave comments, you need to log in
#include <unistd.h>
int main()
{
int fd[2][2];
pipe(fd[0]);
pipe(fd[1]);
pid_t pid_fork = fork();
if (!pid_fork) {
// Дочерний процесс
close(fd[0][1]);
close(fd[1][0]);
dup2(fd[0][0], STDIN_FILENO);
dup2(fd[1][1], STDOUT_FILENO);
execl("/bin/tr", "/bin/tr", "l", "r", NULL);
} else {
// Родительский процесс
close(fd[0][0]);
close(fd[1][1]);
char buf[1000];
ssize_t sz;
write(fd[0][1], "hello, world\n", sizeof("hello, world\n") - 1);
close(fd[0][1]);
sz = read(fd[1][0], buf, sizeof(buf));
if (sz > 0) {
write(STDOUT_FILENO, buf, sz);
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question