我正在尝试将子进程的输出链接到父进程的输入;父进程将使用子进程的输出执行系统调用或命令。
我已查看以下线程来寻求答案;但是,我并没有完全得到我正在寻找的答案。
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/