-1

我正在尝试将子进程的输出链接到父进程的输入;父进程将使用子进程的输出执行系统调用或命令。

我已经查看了以下主题的答案;但是,我并没有完全得到我正在寻找的答案。

管道 - C++ 管道问题

Linux 管道作为输入和输出

我遇到的问题是父进程中的命令没有被打印到终端。

为什么不将输出打印到终端?我已经在父进程和子进程中关闭了管道的末端。此外,父母的 std_out 没有被修改。

这是我的代码。

#include <sys/types.h>
#include <sys/wait.h>  
#include <stdio.h>     
#include <stdlib.h>   
#include <unistd.h>     
#include <iostream>     

using namespace std;

int main(int argc, const char * argv[])
{
    enum {RD, WR};
    int fd[2];
    pid_t pid;

    if (pipe(fd) < 0)
        perror("pipe error");
    else if ((pid = fork()) < 0)
        perror("fork error");
    else if (pid == 0) { //In child process
        close(fd[RD]);
        dup2(fd[WR], STDOUT_FILENO);
        close(fd[WR]);
        execlp("/bin/ps", "ps", "-A", NULL);
    }
    else { //In parent process
        close(fd[WR]);
        dup2(fd[RD], STDIN_FILENO);
        close(fd[RD]);
        wait(NULL);
        execlp("/bin/wc", "wc", "-l", NULL);
    }
    return 0;
}
4

1 回答 1

0

您不检查execlp.

您确定您的所有程序都在您认为的位置吗?如果我更改"/bin/wc""/usr/bin/wc".

于 2016-04-13T19:29:40.577 回答