简体   繁体   中英

Write data to pipe C++

i need to do something like

echo "data" | cat

Using

echo "data" | my program

And inside my program calls the cat and sends my stdin to the cat stdin and get the stdout from the cat.

I already fork the process, close the write and the read, dup2 them and execl.. So i can get the stdout from it, if i do one execl("/bin/sh", "sh", "-c", "ls -lahtr", NULL) i can get the file list as the output.

but i don't know how to send data, like send the echo data that i read from my stdin and send to the execl("/bin/sh", "sh", "-c", "cat", NULL) stdin and return my echo string.

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sstream>
#include <iostream>

using namespace std;

int main()
{
    int ficheiro_fd;
    int pipe_fd[2];
    char buffer[20];
    int num_bytes;

    pipe(pipe_fd);

    switch ( fork() ) {
    case -1:
        exit(1);
    case 0:
        close(pipe_fd[1]);
        dup2(pipe_fd[0], 0);
        execlp("/usr/bin/base64"," ", NULL);
        break;
    default:
        close(pipe_fd[0]);
        //ficheiro_fd = open("output.txt", O_RDONLY);
    while ((num_bytes = read(fileno(stdin), buffer, 1)) > 0){
            write(pipe_fd[1], buffer, num_bytes);
            }
        close(pipe_fd[1]);
        wait((int*)getpid());
    }

    return 0;
}

With this code i can send some data to the program and it writes on the screen, i want to know how i can get the stdout and send to one variable. Thanks for the help ppl.

Use two pipe() calls before you fork. Those will be the stdin and stdout of your called process. After you fork, in the child process, dup2 the write end of one pipe to stdout (1) and the read end of the other pipe to stdin (0). Close the unused ends of the pipe, then exec your process.

In the parent process, close the unused pipe fds. You'll then have an fd that can be read from with read() corresponding to the child's stdout, and an fd that can be written to, corresponding to the child's stdin.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM