1
我想写交流程序,它是Linux命令ps -aux | sort -r -n -k 5
的等价的,但我没有得到任何输出如何将stdout重定向回到多进程c程序中的终端?
这里是我的代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc, char ** argv){
int pipes[2];
int r;
r = pipe(pipes);
if (r < 0) {
fprintf(stderr, "pipe failed\n\n"); // stderr is a FILE* variable for the standard error file (terminal)
exit(2);
}
int saved_stdout = dup(1);
int pid = fork();
if(pid > 0){
// Parent
pid = fork();
if(pid > 0){
// Parent
wait(NULL);
}else if (pid == 0){
// Child 1
printf("Child 1\n");
dup2(pipes[1], 1);
close(pipes[0]);
close(pipes[1]);
execlp("/bin/ps", "ps", "-aux", (char*) NULL);
exit(0);
}else{
fprintf(stderr, "FORK FAILED\n\n");
return 1;
}
}else if (pid == 0){
// Child 2
printf("Child 2\n");
dup2(pipes[0], 0);
close(pipes[0]);
close(pipes[1]);
dup2(saved_stdout, 1);
close(saved_stdout);
execlp("/bin/sort", "sort", "-r", "-n", "-k", "5", (char*)NULL);
exit(0);
}else{
fprintf(stderr, "FORK FAILED\n\n");
return 1;
}
wait(NULL);
printf("Exiting parent\n");
}
我得到的输出是这样的
Child 1
Child 2
Exiting parent
我实际上没有打印execlp
命令,我试过将stdout
保存到变量saved_stdout
,这是我在另一个答案中找到的解决方案,但这样做似乎没有工作。
如何将stdout重定向回终端?
我仍然得到相同的输出,这里是我的代码与我认为你建议https://pastebin.com/G57udtMq的改变,这是正确的吗? –
@MthetheDrill你确定你的'/ bin/ps'和'/ bin/sort'在这里并且工作吗?因为你不检查'execlp()'是否工作。 – Stargateur
我可以运行'ps -aux |命令sort -r -n -k 5'成功在我的终端 –