我正在尝试将子进程的输出链接到父进程的输入。父进程将使用子进程的输出执行系统调用或命令。
我已经在以下线程中寻找答案;但是,我没有完全找到所需的答案。
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"
,则您的程序对我有用。