/* child.c from matt welsh -- Feb. 1995 Linux Journal */

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/time.h>
#include "child.h"

/* exec the named cmd as a child process, returning two
   pipes to communicate with the process, and the child's
   process id */

int start_child(cmd, readpipe, writepipe) 
     char *cmd;
     FILE **readpipe, **writepipe;
{
  int childpid, pipe1[2], pipe2[2];

/* pipe[0] is reading, pipe[1] is writing */
  
  if ((pipe(pipe1) < 0) || ( pipe(pipe2) < 0)) {
    perror("pipe"); 
    exit (-1);
  }

  if ((childpid=vfork()) < 0) {
    perror("fork");
    exit (-1);
  }
  else if (childpid > 0) { /* we are parent */
    close(pipe1[0]);
    close(pipe2[1]);

    /* write to child is pipe1[1], read from child is
       pipe2[0]. */

    *writepipe = fdopen(pipe1[1],"w");
    *readpipe = fdopen(pipe2[0],"r");

/* setlinebuf not portable
    setlinebuf(*writepipe);
*/
    setvbuf(*writepipe, NULL, _IOLBF,0);
    return childpid;

  }
  else {   /* we're the child */
    close(pipe1[1]);
    close(pipe2[0]);

    /* read from parent is pipe1[0],
       write to parent is pipe2[1] */

    dup2(pipe1[0],0);
    dup2(pipe2[1],1);
    close(pipe1[0]);
    close(pipe2[1]);

    if (execlp(cmd,cmd,NULL) < 0) perror("execlp");

/* never returns */

  }
}


