2012-05-25 46 views
0

當我用ls | head執行此函數時,在打印出文件和目錄後,它掛在第二個子進程中。有人能告訴我我在這裏想念什麼嗎?在此先感謝子進程掛在管道內

int unipipe(char* lhs[], char* rhs[]) 
{ 
    int pfd[2]; 
    int status, cid; 
    pid_t pid; 
    char buf; 
    if((lhs != NULL) && (rhs != NULL)) 
    { 
     if(pipe(pfd) != 0) 
     { 
     perror("pipe"); 
     return -1; 
     } 
    if((pid = fork()) < 0) 
    { 
     perror("fork"); 
     return -1; 
    } 
    else if(pid == 0) 
    { 
     close(1); //close the unused read end 
     dup2(pfd[1], STDOUT_FILENO); 
     //execute the left-hand side command 
     close(pfd[0]); 
     execvp(lhs[0], lhs); 
     _exit(EXIT_SUCCESS); 
    } 

    if(setpgid(pid, 0) < 0) 
    { 
    perror("setpgid"); 
    return -1; 
    }; 

    cid = waitpid(pid, &status, 0); 
    if((pid = fork()) == 0) 
    { 
     close(0); 
     dup2(pfd[0], STDIN_FILENO); 
     close(pfd[1]); //close the unused write end 
     execvp(rhs[0], rhs); 
     _exit(EXIT_SUCCESS); 
    } 
    else 
    { 
      waitpid(pid, &status, 0); 
    } 
} 
+1

函數unipipe在哪裏適合你的'ls | head'?祝你好運。 – shellter

+0

我有一個函數調用解析器,它將命令「ls | head」解析爲兩個char指針數組:lhs將是{「ls」,null},rhs是{「head」,null}。感謝您的回覆! – jctank

回答

1

您等待第一個進程退出,然後再開始第二個進程。每個管道都有一個緩衝區,一旦這個緩衝區滿了,I/O功能就會被阻塞,等待從管道中讀取幾個字節,這樣就可以有更多的「流入」。機會是你的第一個過程阻塞管道,因此永遠不會退出。

我會聲明兩個類型爲pid_t的變量,每個孩子一個,並且只有在兩個變量都成功啓動後纔等待它們。

+0

太棒了!這有效,非常感謝! – jctank

0

讓你的程序運行,刪除第一個:

cid = waitpid(pid, &status, 0); 

在:

else 
{ 
     waitpid(pid, &status, 0); 
} 

你將其替換爲:

wait(); // for the fist child 
wait(); // for the second child 

你的程序將運行。