/* dtwin2.c - One of two programs that use named pipes (or FIFOs)
 *            The other program is dtwin1.c.
 *            After you have compiled both programs into images dtwin1
 *            and dtwin2, execute both in the background passing
 *            as only parameters the names you want to use for the fifos.
 *            For example, you could use the names
 *                named_pipe_fifo1 named_pipe_fifo2
 *            dtwin1 will write to dtwin2 two lines from a 
 *            limerick and then print out what dtwin2 sends. 
 *            dtwin2 will read from the fifo and print out the 
 *            info and then send 3 lines to dwin1.
 *            Whichever twin you launch first, it will
 *            hang in there until the other twin is launched. Then
 *            the communication takes place and both twins die.
 */

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

#define MAXBUFFER 256

int
main(int argc, char *argv[])
{
  int fdin, fdout;
  int lcv;
  char buffer[MAXBUFFER];
  int len;
  const int N = 3;
  char *lines[] = {"\nthis is the time\n",
                   "\nwhen all good men\n",
                   "\nthink of their homes\n"}; 
  
  if (argc != 3) {
    printf("usage: twin2 name-of-fifo1 name-of-fifo2\n");
    exit(0);
  }
  if ((mkfifo(argv[1], S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH)<0) 
      && (errno != EEXIST)) {
    perror("mkfifo1 in dtwin2");
    exit(0);
  }
  if ((mkfifo(argv[2], S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH)<0) && 
      (errno != EEXIST)) {
    perror("mkfifo2 in dtwin2");
    exit(0);
  }
  if ((fdin = open(argv[1], O_RDONLY))<0) {
    perror("open fifo1 in dtwin2");
    exit(0);
  }
  while ((len = read(fdin,buffer))>0) {
    printf("%s", buffer);
  }
  close(fdin);
  if ((fdout = open(argv[2], O_WRONLY))<0) {
    perror("open fifo2 in dtwin2");
    exit(0);
  }
  for (lcv = 0; lcv < N; lcv++){
    if (write(fdout, lines[lcv], sizeof(lines[lcv])) <= 0) {
      perror("write problem in dtwin2");
    }
  }
  close(fdout);
}
