将数据写入管道c++

Write data to pipe C++

本文关键字:管道 c++ 数据      更新时间:2023-10-16

我需要做一些像

echo "data" | cat
使用

echo "data" | my program

在我的程序中调用cat并将我的标准输入发送给cat标准输入并从cat获得标准输出

我已经fork了进程,关闭了写和读,dup2和execl..所以我可以从中得到标准输出,如果我执行一个execl("/bin/sh", "sh", "-c", "ls -lahtr", NULL),我可以得到文件列表作为输出。

但我不知道如何发送数据,比如发送我从stdin读取的echo数据并发送到execl("/bin/sh", "sh", "-c", "cat", NULL) stdin并返回我的echo字符串。

#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;
}

有了这个代码,我可以发送一些数据到程序,它写在屏幕上,我想知道我如何能得到标准输出和发送到一个变量。谢谢你的帮助ppl.

在fork之前使用两个pipe()调用。这些将是被调用进程的标准输入和标准输出。fork之后,在子进程中,将一个管道的写端设置为stdout(1),将另一个管道的读端设置为stdin(0)。关闭管道中未使用的末端,然后执行进程。

在父进程中,关闭未使用的管道fds。然后,您将拥有一个可以通过read()读取的fd(对应于子进程的标准输出)和一个可以写入的fd(对应于子进程的标准输出)。