【问题标题】:C multiple processes writing to 1 pipeC多个进程写入1个管道
【发布时间】:2014-05-18 06:56:03
【问题描述】:

你好Linux系统(Centos 6.5)

我创建了一个管道,然后尝试派生多个子进程。我希望子进程写入同一个分叉。 (我不关心同步性)。我发现只有第一个分叉的进程可以写入所有后续进程得到“错误的文件描述符” 睡眠调用仅用于调试。

示例代码:

#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 个管道,但我从未在任何地方看到过这种说法。

谢谢

【问题讨论】:

    标签: c linux fork pipe


    【解决方案1】:

    在第一个孩子分叉后,您正在关闭管道的写入端。

    移动

              close(pipes[1]);
    

    for 循环之外。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-27
      • 1970-01-01
      • 2011-07-15
      • 1970-01-01
      相关资源
      最近更新 更多