0
#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

我需要的是最后一个进程在进程 id 47651 而不是 47658 的进程中完成

4

2 回答 2

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);
}
于 2013-11-08T22:09:03.123 回答
0

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

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

于 2013-11-08T22:09:14.293 回答