简体   繁体   中英

C multiple processes writing to 1 pipe

Hi Linux system (Centos 6.5)

I create a pipe and then try to fork a number of child processes. I want the children processes to write to the same fork. (I am not concerned about synchronocity). What I am finding is that only the first forked process can write all subsequent processes get "Bad file descriptor" Sleep calls are for debugging only.

Sample Code:

#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++);
      }
}

Result is pipe write : Success pipe write : Bad file descriptor pipe write : Bad file descriptor pipe write : Bad file descriptor ...

I am presuming you can't have 2 processes writing to 1 pipe but I have never seen that stated anywhere.

Thanks

You are closing the write end of the pipe after the first child has been forked.

Move

          close(pipes[1]);

outside the for loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM