/***************************************************************
From the book "Motif Programming, The Essentials...and More"
by Marshall Brain.
Published by Digital Press, ISBN 1-55558-089-0.
To order the book, call 1-800-DIGITAL and ask for EY-J816E-DP.

Copyright 1992, by Digital Equipment Corp.

This is the implementation of the link library. 
***************************************************************/

/* link.c */

/* Link module, v1.0, 5/4/91 Marshall Brain */

#include "link.h"

link_open(struct link_handle *l, char name[],char param1[])
{
  pipe(l->pipefd1);
  pipe(l->pipefd2);
  if((l->pid=fork())==0)/*child*/
  {
    close(l->pipefd1[0]);
    close(1);
    dup(l->pipefd1[1]);
    close(2);/*2 new lines*/
    dup(l->pipefd1[1]);
    close(l->pipefd2[1]);
    close(0);
    dup(l->pipefd2[0]);
    execlp(name,name,param1,(char*)0);
fprintf(stdout,"exec.\n");
  }
  else
  {
    l->fpin=fdopen(l->pipefd1[0],"r");
    l->fpout=fdopen(l->pipefd2[1],"w");
    close(l->pipefd1[1]); 
    close(l->pipefd2[0]);
fprintf(stdout,"fork.\n");
  }
}

link_close(struct link_handle *l)
{
  wait((union wait*)0);
  close(l->pipefd1[1]);
  close(l->pipefd2[0]);
  fclose(l->fpin);
  fclose(l->fpout);
  l->pid=0;
}

int link_read(struct link_handle *l,char s[])
{
  int eof_flag;

  if (fgets(s,100,l->fpin)==NULL)
    eof_flag=1;  /* linked-to process has terminated on its own. */
  else
  {
    s[strlen(s)-1]='\0'; /* lose the newline character. */
    eof_flag=0;
  }
  return(eof_flag);
}

int link_input_waiting(struct link_handle *l)
{
  int num;

 fprintf(stdout,"io:%d\n",ioctl(l->pipefd1[0],FIONREAD,&num)); /* see how many chars in buffer. */
fprintf(stdout,"%d %d\n",FIONREAD,I_NREAD);
  return num;
}

link_write_char(struct link_handle *l,char c)
{
  fprintf(l->fpout,"%c",c);
  fflush(l->fpout);
}

link_write(struct link_handle *l,char s[])
{
  fprintf(l->fpout,"%s\n",s);
  fflush(l->fpout);
}

link_kill(struct link_handle *l)
{
  kill(l->pid,SIGKILL);
  link_close(l);
}
