2014-05-18 106 views
2

您好Linux系統(Centos 6.5)C多個進程寫入1管道

我創建一個管道,然後嘗試分叉一些子進程。我想讓子進程寫入同一個分支。 (我不關心同步)。我發現只有第一個分支進程可以寫入所有後續進程獲得「錯誤文件描述符」 睡眠調用僅用於調試。

示例代碼:

#include <stdio.h> 
#include <unistd.h> 
#include <stdlib.h> 
#include <errno.h> 
#include <string.h> 
#include <err.h> 

int  pipes[2]; 
#define FOREVER for(;;) 

int main(int argc, char *argv[]) 
{ 

    int rc; 
    int k; 
    int nbytes; 

    char buffer[4096]; 

    rc = pipe(pipes); 
    if (rc <0) { perror(" Main error with pipes \n"); exit(2); } 

    for (k = 0; k < 10; k++) 
     { 
      rc = fork(); 
      if (rc < 0) { perror(" Main error with pipes \n"); exit(2); } 
      if (rc == 0) 
      { 
       /* Child */ 
       close(pipes[0]); 
       sleep(1); 
       sprintf(buffer,"%d",k); 
       printf("Buffer = ^^%s^^\n",buffer); 
       rc = write(pipes[1], buffer, (strlen(buffer)+1)); 
       perror(" Write result "); 
       exit(0); 
      } 
     else 
      { 
       /* Parent */ 
       close(pipes[1]); 
      } 
     } 

    k = 0; 
    sleep(2); 

    FOREVER 
     { 
     nbytes = read(pipes[0], buffer, sizeof(buffer)); 
     printf(" piped %d bytes; buffer = ## %s ##k = %d\n",nbytes,buffer,k++); 
     } 
} 

結果是 管道寫:成功 管道寫:壞的文件描述符 管道寫:壞的文件描述符 管道寫:壞的文件描述符 ...

我假設你不能有2個進程寫入1個管道,但我從來沒有見過任何地方說過。

感謝

回答

3

你是第一個孩子後,關閉管道的寫端已經分叉。

移動

  close(pipes[1]); 

for循環之外。