/*
 * redir2tub.c
 * cree 2 tubes et 2 fils
 * le pere redirige stdout sur le tube 1
 * le fils1 redirige stdin sur le tube 1 
 * et stdout sur le tube 2
 * le pere se recouvre en `ls -t`
 * le fils1 en `sort`
 * le fils2 en `head -15`
 ****************************************
 * Davy Dequidt
 * L3 Info Luminy
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>

int main(void)
{
  int p1[2], p2[2];
  int pid1 = -1, pid2 = -1;
  if( pipe(p1) || pipe(p2)  ){
    perror("PIPE");
    close(p1[0]);
    close(p1[1]);
    close(p2[0]);
    close(p2[1]);
    exit(1);
  }
  pid1 = fork();
  pid2 = fork();
  if( pid1<0 || pid2<0 ){
    perror("FORK");
    close(p1[0]);
    close(p1[1]);
    close(p2[0]);
    close(p2[1]);
    exit(1);
  }
  if( pid1==0 ){ 
    close( 0 );
    if (dup( p1[0] )<0 ){ perror("DUP ENTREE FILS1"); exit(1); }
    close( 1 );
    if (dup( p2[1] )<0 ){ perror("DUP SORTIE FILS1"); exit(1); }
    close(p1[0]);
    close(p1[1]);
    close(p2[0]);
    close(p2[1]);
    execlp( "sort", "sort", NULL );
    perror("RECOUVREMENT FILS1");
    exit(1);
  }
  if( pid2==0 ){
    close( 0 );
    if ( dup( p2[0] )<0 ){ perror("DUP ENTREE FILS2"); exit(-1); }
    close(p1[0]);
    close(p1[1]);
    close(p2[0]);
    close(p2[1]);
    execlp( "head", "head", "-15", NULL );
    perror("RECOUVREMENT FILS2");
    exit(1);

  }
  if( pid1>0 && pid2>0 ){   
    close( 1 );
    if ( dup( p1[1])<0 ){ perror("DUP SORTIE PERE"); exit(-1); }
    close(p1[0]);
    close(p1[1]);
    close(p2[0]);
    close(p2[1]);
    execlp( "ls", "ls", "-t", NULL );
    perror("RECOUVREMENT PERE");
    exit(1);
  }
  return 0;
}

