#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
#include <errno.h>


int main (int argc, char *argv[], char *envp[]) {
  int pip[2];
  int pid;

  int pos = 0, i;				

  while (pos < argc) {
    if (0 != strcmp("|", argv[pos])) pos++; 
    else break;   
 }
  
  if (pos == argc) {
    fprintf(stderr, "Usage: %s command1 \\| command2\n", argv[0]);
    exit (-1);
  }

  if (-1 == pipe(&pip[0])) {           /*open a pipe*/
    perror("Pipe open error");
    exit (-1);
  }

  if (-1 == (pid = fork())) {           /* fork here */
    perror("Fork error");
    exit (-2);
  }
    
  if (pid > 0) {                        /* parent process*/
    if (-1 == dup2(pip[1], 1)) {        /* replace sdtout */
       perror("Parent dup2 error");      
       kill(pid, SIGKILL);              /* kill the child if error*/
       exit(-3);                        /* and exit */
    }
    close(pip[0]); close(pip[1]);       /* close the pipe */

    argv[pos] = NULL;
    argv ++;
    if (-1 == execvp(argv[0], argv)) {
       perror("Parent cannot exec");      
       kill(pid, SIGKILL);             /* kill the child if error*/
       exit(-3);                        /* and exit */
    }
  } 
  else {                                /* child process*/
    dup2(pip[0], 0);
    close(pip[0]); close(pip[1]);       /* close the pipe */

    for (i=0; i+pos+1<argc; i++) argv[i] = argv[pos+i+1];
    argv[i] = NULL;

    if (-1 == execvp(argv[0], argv)) {
       perror("Child cannot exec");      
       exit(-3);                        /* and exit */
    }
  }
}
