2013-02-21 64 views
1

我想說這個事實,我沒有正式的使用pipes的教育,所以這是我第一次冒險。更何況,我無法找到任何類似的問題,我的情況。C Unix - fork(),execl()和管道在一個循環中

注:這是一個較大的學校任務項目的一部分,所以我不要求任何人爲我這樣做。我只想要一些方向/有用的代碼段。 (我試圖使這一儘可能通用,以避免出現「騙子」的言論。)

我試圖運行for-loop超過int k元素在父進程生成關閉k兒童fork()execl(),然後用一個pipe()發送輸出回到父。下面是我想使用中,我遇到一些通用代碼和錯誤/問題:

注:helloworld =與GCC編譯可執行產生printf("hello world\n");

int k = 10; //The number of children to make 
int fd[2]; //Used for each pipe 
int readFromMe[k]; //Holds the file IDs of each pipe fd[0] 
int writeToMe[k]; //Holds the file IDs of each pipe fd[1] 
int processID[k]; //Holds the list of child process IDs 

//Create children 
int i; 
for(i = 0; i < k; i++) 
{ 
    if(pipe(fd) == -1) 
    { 
     printf("Error - Pipe error.\n"); 
     exit(EXIT_FAILURE); 
    } 

    //Store the pipe ID 
    readFromMe[i] = fd[0]; 
    writeToMe[i] = fd[1]; 

    if((processID[i] = fork()) == -1) 
    { 
     fprintf(stderr, "fork failure"); 
     exit(EXIT_FAILURE); 
    } 

    //If it is a child, change the STDOUT to the pipe-write file descriptor, and exec 
    if(processID[i] == 0) 
    { 
     dup2 (writeToMe[i], STDOUT_FILENO); 
     close(readFromMe[i]); 

     execl("./helloworld", (char *)0); 
    } 

    //If it is the parent, just close the unnecessary pipe-write descriptor and continue itterating 
    else 
    { 
     close(writeToMe[i]); 
    } 
} 

//Buffer for output 
char output[100000]; 

//Read from each pipe and print out the result 
for(i = 0; i < k; i++) 
{ 
    int r = read(readFromMe[i], &output, (sizeof(char) * 100000)); 

    if(r > 0) 
    { 
     printf("result = %s\n", output); 
    } 

    close(readFromMe[i]); 
} 

我沒有得到任何來自輸出我程序,所以我想弄清楚爲什麼會發生這個問題。

+0

檢查exec是否成功,並檢查讀取是否返回0或-1,如果-1檢查errno。 – 2013-02-21 05:53:03

+0

該execl肯定是造成這個問題。 – MrHappyAsthma 2013-02-21 05:59:18

回答

1

或許無關緊要,但你撥打execl錯誤。程序之後的額外參數是argv陣列對其他程序main函數的作用。正如你所知,它總是有一個入口,程序名稱。所以你需要這樣稱呼它:

execl("./helloworld", "helloworld", NULL); 

更多與您的問題相關的,你也應該檢查錯誤,它可能實際上失敗。

+0

它提到在其他問題中將「NULL」標記投射到(char *),並且似乎沒有引起問題。我也更新了缺失的參數。謝謝:) – MrHappyAsthma 2013-02-21 05:56:09

+1

@MHHappyAsthma不要改變問題來反映解決方案。這很混亂。 – 2013-02-21 06:13:15

1

嘗試在打印輸出功能中打印'r'的值。我懷疑閱讀是返回一個錯誤(也許EPIPE),你沒有看到。此外,你的例子代碼試圖printf'c',而不是像你看起來那樣輸出。

+0

這是一個複製/粘貼錯字「c」而不是「輸出」。我不希望我的作業在網上發佈逐字:P但是在檢查「r」後,事實證明這只是execl的一個問題。 – MrHappyAsthma 2013-02-21 06:04:24