Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C多个进程写入一个管道_C_Linux_Fork_Pipe - Fatal编程技术网

C多个进程写入一个管道

C多个进程写入一个管道,c,linux,fork,pipe,C,Linux,Fork,Pipe,Hi-Linux系统(Centos 6.5) 我创建一个管道,然后尝试分叉多个子进程。我希望子进程写入同一个fork。(我不关心同步性)。我发现只有第一个分叉进程可以写入所有后续进程,并获得“坏文件描述符” 睡眠调用仅用于调试 示例代码: #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <errno.h> #include <string.h> #i

Hi-Linux系统(Centos 6.5)

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

示例代码:

#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++);
      }
}
#包括
#包括
#包括
#包括
#包括
#包括
int管道[2];
#为(;;)定义永久
int main(int argc,char*argv[])
{
int rc;
int k;
整数字节;
字符缓冲区[4096];
rc=管道(管道);

如果(rc您在分叉第一个子级之后关闭管道的写入端

移动


循环的
之外。

在第一个子循环分叉后,您将关闭管道的写入端

移动

for
循环之外

          close(pipes[1]);