#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <signal.h>

#define BUFSIZE	4096

int fortune(char *fifo)
{
  char buf[BUFSIZE];
  int sv[2], fd, r, i;
  pid_t pid;

  if ((fd = open(fifo, O_WRONLY)) < 0) {
    perror("opening file");
    return 0;
  }

  if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) < 0) {
    perror("socketpair");
    return 0;
  }

  pid = fork();
  if (pid < 0) {
    perror("fork");
    return 1;
  } else if (pid > 0) {
    close(sv[1]);
    write(fd, "---\n", 4);
    while((r = read(sv[0], buf, BUFSIZE)) > 0) {
      if (write(fd, buf, r) < 0) break;
    }
    close(sv[0]);
    close(fd);
  } else {
    close(sv[0]);
    dup2(sv[1], 0);
    dup2(sv[1], 1);
    dup2(sv[1], 2);
    close(sv[1]);
    execl("/usr/games/fortune", "fortune", NULL);
    perror("exec");
  }
  return 1;
}

int main(int argc, char *argv[])
{
  struct sigaction act;
  
  act.sa_handler = SIG_IGN;
  sigaction(SIGPIPE, &act, NULL);

  if (argc < 2) {
    fprintf(stderr,"Usage: serv <fifo>\n");
    return 0;
  }

  while(fortune(argv[1]));

  return 0;
}