 /* dtwin1.c - One of two programs that use named pipes (or FIFOs)
 *            The other program is dtwin2.c.
 *            After you have compiled both programs into images dtwin1
 *            and dtwin2, execute both in the background passing
 *            as only parameter the names you want to use for the fifos
 *            they use to communicate back and forth.
 *            For example, you could use the name
 *                named_pipe_fifo1 and named_pipe_fifo2
 *            dtwin1 will write to dtwin2 two lines from a 
 *            limerick and then read from the other fifo. 
 *            dtwin2 will read from the fifo and print out the info and then 
 *            write a message to the other fifo.
 *            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;
  int len;
  char buffer[MAXBUFFER];
  const int N = 2;
  char *lines[] = {"\nroses are red\n",
                   "\nviolets are blue\n"};
  

  if (argc != 3) {
    printf("usage: dtwin1 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");
    exit(0);
  }
  if ((mkfifo(argv[2], S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH)<0) 
      && (errno != EEXIST)) {
    perror("mkfifo2");
    exit(0);
  }
  if ((fdout = open(argv[1], O_WRONLY))<0) {
    perror("open in dtwin1, file1");
    exit(0);
  }
  for (lcv = 0; lcv < N; lcv++){
    if (write(fdout, lines[lcv], sizeof(lines[lcv])) <= 0) {
      perror("write problem in dtwin1");
    }
  }
  close(fdout);
  if ((fdin = open(argv[2], O_RDONLY))<0) {
    perror("open in dtwin1, file2");
    exit(0);
  }
  while ((len=read(fdin,buffer))>0) {
    printf("%s", buffer);
  }
  close(fdin);
  if (remove(argv[1])<0){
    perror("remove in dtwin1 for fifo1");
  }
  if (remove(argv[2])<0){
    perror("remove in dtwin1 for fifo2");
  }
}
