【问题标题】:Write data to pipe C++将数据写入管道 C++
【发布时间】:2012-01-28 01:16:54
【问题描述】:

我需要做类似的事情

echo "data" | cat

使用

echo "data" | my program

在我的程序内部调用 cat 并将我的标准输入发送到 cat 标准输入并从 cat 获取标准输出。

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

但我不知道如何发送数据,例如发送从标准输入读取的回显数据并发送到 execl("/bin/sh", "sh", "-c", "cat" , NULL) 标准输入并返回我的回显字符串。

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

使用此代码,我可以将一些数据发送到程序并在屏幕上写入,我想知道如何获取标准输出并发送到一个变量。 谢谢大家的帮助。

【问题讨论】:

  • 看起来你在做一些完全没用的事情。请显示一些代码。
  • 你能分享你的代码吗?你的问题有点复杂。一般来说,管道只有一种方式,一个进程读取而另一个进程写入,您不能通过同一管道将数据从读取器发送回写入器。所以你可以做回声数据|你的程序 | cat ... 会将您程序的标准输出传递给 cat 的标准输入...
  • 您好,我分享了代码,我需要的原因是我要通过套接字发送一个命令,我需要在另一端处理我的输入并获得返回。

标签: c++ process pipe stdin


【解决方案1】:

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

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

【讨论】:

  • 注意,我需要通过套接字将数据发回,我如何获得execl处理的数据?
猜你喜欢
  • 1970-01-01
  • 2015-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多