Linux C中循环中的分叉和管道进程

时间:2013-11-08 21:55:52

标签: c fork pipe

#include <stdio.h>
#include <sys/types.h> 
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/wait.h>


int main() 
{  
  int pfd[2];  
  int status,i;  
  char input[1024];
  int rfds[n]; //Hold the file IDs of each pipe fd[0]
  int wfds[n]; //Holds the file IDs of each pipe fd[1]
  int pids[n]; //Holds the list of child process IDs


  while(fgets(input,sizeof(input),stdin)){   
    for (i=0;i<6;i++){
      if(pipe(pfd) < 0) 
    {  
      printf("Failed to create pipe!\n");  
      return 1;  
    }
      //Store the pipe ID
      rfds[i] = pfd[0];
      wfds[i] = pfd[1];
      if((pids[i] = fork())<0){
    printf("Failed to fork!\n");  
    return 1;  
      }  
      if (pids[i]==0) {    
    close(wfds[i]);
    if(read(rfds[i],input,strlen(input)) > 0)  
      {  
        printf("process #%d (%d) relaying message:%s",i,getpid(),input);
      }
    close(rfds[i]);
    }  
      else  
    {   
      close(rfds[i]);
      if((write(wfds[i], input, strlen(input))) ==-1)  
        {  
          printf("Failed to write!\n");
          return 1;
        }  
        close(wfds[i]);
        wait(&status);  
    }
    } 
  }
  return 0;
}

我对此进行编码以将消息从进程传输到进程。但我想让最后一个进程连接到第一个进程。 即输出的内容就像

process #0 (47652) sending message: MD
process #1 (47653) relaying message: MD
process #2 (47654) relaying message: MD
process #3 (47655) relaying message: MD
process #4 (47656) relaying message: MD
process #5 (47657) relaying message: MD
process #6 (47658) relaying message: MD

我需要的是最后一个流程在流程中完成,流程编号为47651而不是47658

2 个答案:

答案 0 :(得分:1)

在开始分叉之前,您必须创建一个末端管道。因为最后一个进程连接到第一个进程需要这个。

我有一些你可以创建孩子的代码。

void createChildren(int size)
{
    int i = 0;
    int end_pipe[2];        
    int incomming[2];
    int outgoing[2];

    /* create the end pipe */
    pipe(end_pipe);

    for(i = 0; i < size - 1; ++i)
    {
        pipe(outgoing);

        /* parent process */
        if (fork() != 0)
        {
            break;
        }

        /* incomming pipe of the child is the outgoing of the parent */
        incomming[0] = outgoing[0];
        incomming[1] = outgoing[1];     
    }

    /**
     * If master then the incomming pipe is the end pipe. Glue the end to the beginning
     */
    if (i == 0)
    {
        incomming[0] = end_pipe[0];
        incomming[1] = end_pipe[1];
    }   

    /**
     * If master then the ougoing pipe is the end pipe. Glue the end to the beginning
     * Initial write to the ring
     */
    if (i == size - 1)
    {
        int buffer = 0;

        outgoing[0] = end_pipe[0];
        outgoing[1] = end_pipe[1];

        write(outgoing[1], &buffer, sizeof(int));
    }

    runClient(i, size, incomming, outgoing);
}

答案 1 :(得分:0)

只需创建n个管道(您可以使用数组),其中n是进程数。然后每次写入下一个管道并从您自己的管道读取。在循环结束时,只需使用模数就可以保持在管道数组中。

这有帮助吗?我可以给你一些代码,但它不应该太难。