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'成功在我的終端 –