title: How to make a process ring with fork and pipe?
body: <p>Currently I'm learning C and I'd like to make a <strong>ring of <em>n</em> childs</strong> process with forks and pipes where <strong><em>n</em></strong> is a number enter in argument, each child could communicate with the next child in one direction <a href="https://i.stack.imgur.com/tB1gl.png." rel="nofollow noreferrer">like this.</a>
  I tried to do it where each child send to the next child its pid but I don't get what I want for instance if I create 3 childs :</p>
  
  <ol>
  <li>PID:1,i in loop : 0, received : 0</li>
  <li>PID:2, i in loop : 1, received : 0</li>
  <li>PID:3, i in loop : 2, received : 0</li>
  </ol>
  
  <p>But I should get :</p>
  
  <ol>
  <li>PID:1,i in loop : 0, received : 3</li>
  <li>PID:2, i in loop : 1, received : 1</li>
  <li>PID:3, i in loop : 2, received : 2</li>
  </ol>
  
  <p>Sometimes I receive a value from one random child to another here is my code, I'm not really comfortable with multiples pipes in a loop.</p>
  
  <pre><code>#include &lt;errno.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;fcntl.h&gt;              
  #include &lt;unistd.h&gt;
  
  int main(int argc, const char * argv[]) {
      if(argc != 2) {
          fprintf(stderr, "Usage : %s &lt;integer&gt; [&gt; 2]\n", argv[0]);
          exit(EXIT_FAILURE);
      }
  
      int number_process = atoi(argv[1]);
      if(number_process &lt; 2) {
          fprintf(stderr, "Usage : %s &lt;integer&gt; [&gt; 2]\n", argv[0]);
          exit(EXIT_FAILURE);
      }
  
      printf("Création de %d processus pour une élection : \n", number_process);
      int i = 0, j = 0, k = 0;
      int * t = (int *) malloc((2 * number_process) * sizeof(int));
  
      for(k = 0; k &lt; number_process; k++) {
          pipe(&amp;t[2*i]);
      }
  
      for(i = 0; i &lt; number_process; i++) {
          if(fork() == 0) {
              for(j = 0; j &lt; number_process*2; j++) {
                  if(j != 2*i &amp;&amp; j != ((2*i+3)%(number_process*2))) {
                      close(t[j]);
                  }
              }
              close(t[(2*i+1)%(number_process*2)]);
              close(t[((2*i+2)%(number_process*2))]);
  
              int pid = (int) getpid();
              write(t[(2*i+3)%(number_process*2)], &amp;pid, sizeof(int));
  
              int in = 0;
              read(t[i*2], &amp;in, sizeof(int));
              printf("%d : %d\n", in, getpid()); 
  
              exit(EXIT_SUCCESS);
          }
      }
      return (EXIT_SUCCESS);
  }
  </code></pre>