2011-10-23 49 views
0

我嘗試使三個進程管道彼此。然而,我對第三個過程感到困惑。分叉和管道只有兩個過程工作沒有問題。當我添加+1循環來測試第三個進程是否會產生時,我會在終端中得到奇怪的結果。分叉三個子進程給出奇怪的隨機輸出

這是我的代碼(與怪異的結果):

#include <stdio.h> 
#include <sys/types.h> 
#include <sys/wait.h> 
#include <unistd.h> 

int main(){ 

    int status, i; 
    int pip[2]; 


    /* Spawn 3 subprocesses and pipe the first 2*/ 
    for (i=0; i<3; i++){ 

    if (i==0) pipe(pip); 

    if (fork()==0){ 

     /* First subprocess */ 
     if (i==0){ 
     dup2(pip[1], 1); //pip[0] will replace stdout 
     close(pip[0]); 
     if (execlp("ls", "ls", NULL)) perror("process1"); 
     } 

     /* Second subprocess */ 
     if (i==1){ 
     dup2(pip[0], 0); //pip[1] -> will replace stdin 
     close(pip[1]); 
     if (execlp("more", "more", NULL)) perror("process2"); 
     } 

     /* Third subprocess */ 
     if (i==2){ 
     close(pip[0]); //reseting fd 
     close(pip[1]); //reseting fd 
     open(0);  //reseting fd 
     open(1);  //reseting fd 
     if (execlp("ls", "ls", NULL)) perror("process3"); 
     } 


    } 
    } 

    wait(&status); 
    return 0; 
} 

改變for循環,以2環,而不是3停止怪異的行爲。 怪異的行爲是隨機我會在終端其中一個輸出:

[email protected]:~/Desktop/test$ ./test 
test test2.c test3.c test4.c test.5c test.c 
test 
test2.c 
test3.c 
test4.c 
test.5c 
test.c 
[email protected]:~/Desktop/test$ 

在其擔任通常這種情況下。現在在某些點上它是這樣的:

[email protected]:~/Desktop/test$ test 
test2.c 
test3.c 
test4.c 
test.5c 
test.c 
test test2.c test3.c test4.c test.5c test.c 
[email protected]:~/Desktop/test$ [email protected]:~/Desktop/test$ [email protected]:~/Desktop/test$ [email protected]:~/Desktop/test$ [email protected]:~/Desktop/test$ 

打到哪裏只是寫入提示並等待更多的輸入。第三個奇怪的行爲是這樣的:

[email protected]:~/Desktop/test$ test 
test2.c 
test3.c 
test4.c 
test.5c 
test.c 
(blinking prompt symbol) 

一旦我點擊進入程序正常結束。有人可以解釋發生了什麼嗎?

回答

3

open(0);

open(1);

請閱讀man page打開(2)。

提示:它不需要一個參數。您應該使用-Wall來構建,並注意編譯器警告。

這可能不能完全解釋你所看到的,但鑑於這個明顯的錯誤,我懶得再看。

+0

忘了 - 牆。將看看我是否從中得到了什麼。 – Pithikos