'Child Process not reading / executing from pipe input

I want to make communication between N child processes thro N-1 pipes. And as far as I understood, you should have the following setup for N=3:

Process_1

  • read from standard input (inherited from parent)
  • write into first pipe

Process_2

  • reads from first pipe
  • writes into second pipe

Process_3

  • reads from second pipe
  • writes into standard output (inherited from parent)

My code is hanging with a command prompt after the printf in main. Im honest, I havent really looked thro the closing of pipes fully yet, because often its written you just have to close both ends all the time. So I close both ends, but its waiting still, or something else if off.

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

#define WRITE 1
#define READ 0

void three_processes_ipc(){
   int fd[2][2];
   pipe(fd[0]);
   pipe(fd[1]);
   pid_t pid[3];
   /* first process */
   pid[0] = fork();
   if (pid == 0)
   { 
   dup2(fd[0][WRITE], WRITE);   
   close(fd[0][WRITE]); close(fd[0][READ]);
   char *arguments[] = {"ls", "-l", "-a", NULL};
   execvp(arguments[0], arguments);
   perror("command failed: "); exit(1);
   }
   /* second process */
   pid[1] = fork();
   if (pid[1] == 0)
   {
      dup2(fd[0][READ], READ); 
      dup2(fd[1][WRITE], WRITE); 
      close(fd[1][WRITE]); close(fd[0][READ]);
      char *arguments[] = {"grep", "Mai", NULL};
      execvp(arguments[0], arguments); exit(1);
   }
   /* third process */
   pid[2] = fork();
   if (pid[2] == 0)
   {
      dup2(fd[1][READ], READ); 
      close(fd[1][WRITE]); close(fd[1][READ]);
      char *arguments[] = {"cat", NULL};
      execvp(arguments[0], arguments);
      perror("command failed: "); exit(1);
   }
   waitpid(pid[0], NULL, 0);
   waitpid(pid[1], NULL, 0);
   waitpid(pid[2], NULL, 0);
}


int main(void){
    printf("three_processes_ipc()\n");
    three_processes_ipc();
    return 0;
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source