2014-03-19 51 views
0

我想與父進程溝通子進程。我創建了5個孩子,每個人都發送給管道消息「你好」。但parrent只讀一個消息..我很初學者,我不知道我做錯了什麼......我到目前爲止的代碼:家長不從管道讀取

int main(int argc, char** argv) { 
    int n, p1[2], p2[2]; 
    n = 2*atoi(argv[1]); 
    if(pipe(p1)) ERR("pipe1"); 
    if(pipe(p2)) ERR("pipe2"); 
    create_children(n, p1, p2); 
     if(TEMP_FAILURE_RETRY(close(p1[1]))) ERR("close"); 
    parent_work(p1); 
    if(TEMP_FAILURE_RETRY(close(p1[0]))) ERR("close"); 
    return EXIT_SUCCESS; 
} 

void create_children(int number, int p1[2], int p2[2]) { 
    while (number-- > 0) { 
     switch (fork()) { 
      case 0: 
       if(TEMP_FAILURE_RETRY(close(p1[0]))) ERR("close"); 
       if(TEMP_FAILURE_RETRY(close(p2[0]))) ERR("close"); 
       child_work(p1[1], p2[1]); 
       if(TEMP_FAILURE_RETRY(close(p1[1]))) ERR("close"); 
       if(TEMP_FAILURE_RETRY(close(p2[1]))) ERR("close"); 
       exit(EXIT_SUCCESS); 

      case -1: ERR("Fork:"); 
     } 
    } 
} 

void child_work(int fd, int fd1, char *name, int which) { 
    char buffer[PIPE_BUF]; 
    size_t *len = (size_t*)buffer; 

    char mb[PIPE_BUF]; 
    snprintf(mb,PIPE_BUF,"%d hello\n",getpid()); 
    if (-1 == TEMP_FAILURE_RETRY (write (fd, mb, (strlen(mb)+1))))/
      ERR ("sending witaj"); 
      else 
      printf("%s\n",mb); 
} 

void parent_work(int fd) { 
    char buffer[PIPE_BUF]; 
    if(TEMP_FAILURE_RETRY(read(fd, buffer, PIPE_BUF))==PIPE_BUF)ERR("read:"); 
    printf("Process send message: %s\n", buffer); 

    while(TEMP_FAILURE_RETRY(wait(NULL))>0); 
} 

當我創建5個孩子,我只獲得了1信息。

回答

1

這可不行:

char mb[]=" "; 
snprintf(mb,PIPE_BUF,"%d",getpid()); 
strcat(mb,"hello"); 

你寫過去mb結束,因爲它與一個空格,然後通過一個NULL字節初始化它只有兩個字符空間。在C語言中,當你編寫結尾時,數組不會奇蹟般地增長,就像你使用snprintfstrcat一樣。

從技術上講,你調用了所謂的未定義的行爲,這意味着任何事情都可能發生。

0

孩子們發送空終止的消息,所以如果父母收到一個read中的所有消息,父母將只打印第一條消息。

我建議你讓孩子們發送換行符終止的消息(附加一個\n到發送字符串,不要發送空終止符)。

+0

如果我這樣做: 'char mb [PIPE_BUF]; snprintf(mb,PIPE_BUF,「%d hello \ n」,getpid());' 它不會發送null? – Ann

+0

這樣做,並使用發送長度'strlen(mb)'(而不是'strlen(mb)+ 1')。 –

+0

我仍然沒有得到我想要的東西。父母像你說的一樣接收所有消息,但是我需要寫入「Process send message:%s \ n」,buffer);爲每個子進程分開:( – Ann