2012-02-02 90 views
1

我正在運行一個管道程序。 我想運行的命令是ls |貓。在C中關閉管道,dup2,文件描述符?

int cmd(char** w, int* pipe, int action){ 
... some code up here 
... 
int fd; 
if(child_pid == 0) { 
    if (pipe != 0) { 

     if (action == 0){ 
      fd = dup2(pipe[0], STDIN_FILENO); 
      close(pipe[0]); 
      close(pipe[1]); 
      //close(fd); 
     } 
     else if (action == 1){ 
      fd = dup2(pipe[1], STDOUT_FILENO); 
      close(pipe[0]); 
      close(pipe[1]); 
      //close(fd); 
     } 


    } 

    execvp(w[0], w); 



    printf("Unknown command\n"); 
    exit(0); 
    } 
... some code down here 

當我運行代碼時,命令ls |除了貓沒有結束(即管道不關閉,只是在那裏等待什麼都不做)之外,貓運行得很好。我認爲這是因爲我沒有關閉流或其他東西,但我對C/IO不夠熟悉。我做對了嗎?

運行此函數的代碼是一樣

int fd[2]; 
int p = pipe(fd); 
cmd(w, fd, 1); 
cmd(w, fd, 0); 

編輯:你是對的,fatalerror,我在arguement

thxs拼寫錯誤,貌似我只需要關閉管[1]中parent

回答

3

父進程還需要關閉兩個cmd調用後的管道兩端。

相關問題