2017-06-03 49 views
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重定向回終端?

回答

3

奇怪我用你的代碼輸出爲:

Child 1 
Child 2 

,程序不停止。或者你確定你的輸出是有效的?

無論如何,你的問題是你不會在你的父母關閉你的管道。只需添加:

close(pipes[0]); 
close(pipes[1]); 

在您的父母雙方(在您的兩個電話wait()之前)。

saved_stdout在你的情況下是無用的,因爲你只改變你的child1的stdout。 saved_stdout1描述您的child2中的同一個文件。

+0

我仍然得到相同的輸出,這裏是我的代碼與我認爲你建議https://pastebin.com/G57udtMq的改變,這是正確的嗎? –

+0

@MthetheDrill你確定你的'/ bin/ps'和'/ bin/sort'在這裏並且工作嗎?因爲你不檢查'execlp()'是否工作。 – Stargateur

+0

我可以運行'ps -aux |命令sort -r -n -k 5'成功在我的終端 –

相關問題