title: Dining Philosophers in C using fork()
body: <p>I wrote a C program for the Dining Philosophers Problem using pthread some time ago and am now trying to change it to use fork() instead. This is an exercive for a lecture I already passed. But a friend asked me for help and I can't seem to get it figured out by myself, which is driving me crazy!</p>
  
  <p>If i do a "ps" the processes are there. But there isn't any output to stdout, so I think I'm doing something wrong with the pipes.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;semaphore.h&gt;
  #include &lt;pthread.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;string.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/wait.h&gt;
  
  #define N 5     
  #define LEFT (i+4)%N
  #define RIGHT (i+1)%N
  #define THINKING 0
  #define HUNGRY 1
  #define EATING 2
  
  sem_t spoon;
  sem_t phil[N];
  int state[N];
  int phil_num[N]={0,1,2,3,4};
  int fd[N][2]; // file descriptors for pipes
  pid_t pid, pids[N]; // process ids
  int i; 
  int num;
  
  void philosopher(int i);
  void test(int i);
  void take_spoon(int i);
  void put_spoon(int i);
  
  char buffer[100];
  
  int main(void) 
  {
    for(i=0;i&lt;N;++i)
    {
      pipe(fd[i]);        
      pids[i] = fork();
  
      printf("i=%d\n",i);
      printf("pids[i]=%d\n",pids[i]);
  
      if(pids[i]==0)
      {
        // child
        dup2(fd[i][1],1);
        close(fd[i][0]);      
        close(fd[i][1]);
        philosopher(i);
        _exit(0);
      }
  
      else if(pids[i]&gt;0)
      {
        // parent
        dup2(fd[i][0],0);
        close(fd[i][0]);      
        close(fd[i][1]);
      }
    }
  
    // wait for child processes to end
    for(i=0;i&lt;N;++i) waitpid(pids[i],NULL,0);
  
    return 0;
  }
  
  
  
  void philosopher(int i)
  {
    while(1)
    {
      sleep(1);
      take_spoon(i);
      sleep(2);
      put_spoon(i);
      sleep(1);
    }
  }
  
  void take_spoon(int i)
  {
    sem_wait(&amp;spoon);
    state[i] = HUNGRY;
    printf("philosopher %d is hungry\n",i+1);
    test(i);
    sem_post(&amp;spoon);
    sem_wait(&amp;phil[i]);
  }
  
  void put_spoon(int i)
  {
    sem_wait(&amp;spoon);
    state[i] = THINKING;
    printf("philosopher %d puts down spoon %d and %d hin\n",i+1,LEFT+1,i+1);
    printf("philosopher %d thinks\n",i+1);
    test(LEFT);
    test(RIGHT);
    sem_post(&amp;spoon);
  }
  
  void test(int i)
  {
    if( state[i] == HUNGRY &amp;&amp; state[LEFT] != EATING &amp;&amp; state[RIGHT] != EATING)
    {
      state[i] = EATING;
      printf("philosopher %d takes spoon %d and %d\n",i+1,LEFT+1,i+1);
      printf("philosopher  %d eats\n",i+1);
      sem_post(&amp;phil[i]);
    }
  }
  </code></pre>
  
  <p>Thank you in advance for any help. </p>