2017-06-03 39 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'成功在我的终端 –

相关问题