2013-12-09 33 views
2

我的代碼對我的課程有問題我必須在不同的過程中運行不同的功能,然後將結果傳回父級並顯示出來。我遇到了問題,所以我目前正在嘗試通過在基本程序中執行來理解,但我仍然遇到錯誤。c多個叉子和管子

首先,我不能得到pid = wait(&status);它一直說pid是未定義的,那麼當我開始轉移到管道系統,但信息似乎並未達到父項。

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

#define PROCS 5 

int main(void){ 
    int pipes[PROCS][2]; 
    pid_t ret[PROCS]; 
    int status = 0; 
    int i; 
    char msg[PROCS][100]; 

    for(i = 0;i < PROCS; i++){ 

    //create pipes 
     //create pipes 
     if (pipe(pipes[i]) != 0) { // Create a new pipe. 
      printf("Could not create new pipe %d", i); 
      exit(1); 
     } 

     if ((ret[i] = fork()) == -1) { 
      printf("Could not fork() new process %d\n", i); 
      exit(1); 
     }else if (ret[i] == 0) {//if child 
      close(pipes[i][1]); 
      char string[] = "child process"; //%d - process id = %d\n", i, getpid(); 
      write(pipes[i][0], string, 25); 
      exit(0); 
     } 
    } 
    if(getpid() > 0){ 
     for(i = 0; i < PROCS; i++) { 
      wait(&status); 
     } 
     for(i = 0; i < PROCS; i++) { 
      close(pipes[i][1]); 
      read(pipes[i][0], &msg[i], 100); 
      close(pipes[i][0]);   
     } 
     printf("test 1 : %s\n", msg[0]); 
     printf("test 2 : %s\n", msg[1]); 
     printf("test 3 : %s\n", msg[2]); 
     printf("parent process - process id = %d\n", getpid());  
     exit(0); 
    } 
} 

回答

2
}else if (ret[i] == 0) {//if child 
     close(pipes[i][1]); <== (1) 
     char string[] = "child process"; //%d - process id = %d\n", i, getpid(); 
     write(pipes[i][0], string, 25); <== (2) 
     exit(0); 

    //..... 

    for(i = 0; i < PROCS; i++) { 
     close(pipes[i][1]); 
     read(pipes[i][0], &msg[i], 100); <-- (3) 
     close(pipes[i][0]);   
    } 

按照慣例,[0]管元件是用於讀出和寫入用的[1]的元素。您正在編寫[0],然後在父文件中讀取[0]。解決這個問題,你很好。

if(getpid() > 0){ 

以上是毫無意義的。 getpid()總是將大於0,因爲每個進程的pid都大於零。你想對你在ret [i]中存儲的fork返回的pid做這個測試。在這種情況下,這也是不必要的,因爲你的孩子退出,所以只有父母纔會到達這個代碼。

永遠,永遠,永遠檢查您的返回代碼。如果你曾經直接看到你的管道寫入失敗,你的管道讀取返回0.

+0

thx完美工作,thx指出getpid錯誤,我沒有意識到, –

+0

優秀。按複選標記以接受答案。 – Duck