T
T
temp_str2015-12-30 12:12:34
C++ / C#
temp_str, 2015-12-30 12:12:34

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
{
    // Родительский процесс
}

When initializing the pipe, we have 2 pipe outputs - input and output. When entering at the right end of the pipe (1), we can get the output at the left (0). I tried to run the program through execl in the child process, but then I have no idea how to pass user input to the program input (it is clear that through write), and then where and how to get the program output.
execl("/bin/sh", "sh", "-c", "../sample/main", NULL);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2015-12-30
@temp_str

#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 question

Ask a Question

731 491 924 answers to any question