C 多个进程写入 1 个管道

标签 c linux fork pipe

嗨Linux系统(Centos 6.5)

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

示例代码:

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

谢谢

最佳答案

在第一个子节点被 fork 后,您将关闭管道的写入端。

移动

          close(pipes[1]);

for 循环之外。

关于C 多个进程写入 1 个管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23719374/

相关文章:

c - Hook SIGSEGV 时强制内核转储进程

linux - 如何检测我是否可以在盒子上运行为 gcc4 编译的可执行文件?

c - 隐藏 Execve 的终端输出

algorithm - 在线编译器如何处理 fork 炸弹

c - wait() 调用会以可预测的顺序执行吗?

c - 24小时时间格式

c - 为什么在线评委不接受?

node.js - 哪个 Node 给出了很奇怪的结果

c - While 循环按引用传递字符数组

c - ioctl IOCGIWSCAN : invalid arguments,