2012-05-22 79 views
2

這裏有一個程序,我試圖讓:重定向標準輸出管道用C

#include <stdio.h> 
#include <stdlib.h> 
#include <sys/types.h> 
#include <unistd.h> 
#include <string.h> 



int main(int argc, char* argv[]) 
{ 
    char* arguments[] = {"superabundantes.py", NULL}; 

    int my_pipe[2]; 
    if(pipe(my_pipe) == -1) 
    { 
     fprintf(stderr, "Error creating pipe\n"); 
    } 

    pid_t child_id; 
    child_id = fork(); 
    if(child_id == -1) 
    { 
     fprintf(stderr, "Fork error\n"); 
    } 
    if(child_id == 0) // child process 
    { 
     close(my_pipe[0]); // child doesn't read 
     dup2(my_pipe[1], 1); // redirect stdout 

     execvp("cat", arguments); 

     fprintf(stderr, "Exec failed\n"); 
    } 
    else 
    { 
     close(my_pipe[1]); // parent doesn't write 

     char reading_buf[1]; 
     while(read(my_pipe[0], reading_buf, 1) > 0) 
     { 
      write(1, reading_buf, 1); // 1 -> stdout 
     } 
     close(my_pipe[0]); 
     wait(); 
    } 
} 

我想在孩子重定向孩子的父標準輸出(通過管道)執行EXEC。我認爲這個問題可能與dup2有關,但我之前沒有使用它。

+0

請指定什麼「問題」,而不是隻是傾銷你的代碼,讓我們找出。如果您不知道問題所在,請將錯誤報告添加到您的程序中。 –

+0

不要解決您的問題,但必須爲wait()函數指定int * sts(可以爲NULL)。 –

回答

3

您需要當您調用exec時提供argv[0]。所以你的論據應該是:

char* arguments[] = {"cat", "superabundantes.py", NULL}; 
+0

是的!你是對的。 char * arguments [] = {「cat」,「superabundantes.py」,NULL}; execvp(argv [0],arguments);它完美的工作,謝謝。 – XavierusWolf