c++ - 为什么 execlp() 不将输出打印到终端?

标签 c++ linux pipe unistd.h

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

我已查看以下线程来寻求答案;但是,我并没有完全得到我正在寻找的答案。

Pipe - C++ piping issue

Linux Pipes as Input and Output

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

为什么输出没有打印到终端?我已经关闭了父进程和子进程中管道的末端。此外,父级的 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;
}

最佳答案

您不检查 execlp 是否失败。

您确定您的所有程序都在您认为的位置吗?如果我只需将 "/bin/wc" 更改为 "/usr/bin/wc",您的程序就适合我。

关于c++ - 为什么 execlp() 不将输出打印到终端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36606733/

相关文章:

c - grep : (standard input): Bad file descriptor

c - fork() 子执行命令输出奇怪

c++ - Linux中mremap函数的特点

html - Libreoffice 将 html 转换为 xls 或 xlsx

Bash:检查多管道命令链的退出状态

c++ - 如何使用 Qt C++ 在 QDialog Window 和 QMainWindow 之间进行通信

C++ - 在构造函数中初始化指针数组

c++ - 预订 "Programming Role Playing Games with DirectX 2nd edition"和更新的 DirectX api

c++ - C++ 标准规定的整数范围

linux - 使用 wineprefix 在 XFCE 中制作 winetricks 启动器