#include <stdio.h>
#include <stdlib.h>
#include "socketfun.h"

main(int argc, char **argv)
{
  char *hn;
  int port, sock, fd;
  void doit(int fd);

  if (argc != 3) {
    fprintf(stderr, "usage: serve1 hostname port\n");
    exit(1);
  }

  hn = argv[1];
  port = atoi(argv[2]);
  if (port < 5000) {
    fprintf(stderr, "usage: serve1 hostname port\n");
    fprintf(stderr, "       port must be > 5000\n");
    exit(1);
  }

  sock = serve_socket(hn, port);

  for ( ; ; ) {
 
  	fd = accept_connection(sock);
        printf("received a client connection on %d\n", fd);

        doit(fd);                      /* process the request */

        close(fd);
  }
}

/****************************/
/*
 * doit ( int fd )
 *
 ***************************/

void doit( int fd) 
{
   int saved_stdin, saved_stdout;

   saved_stdin = dup(0);
   saved_stdout = dup(1);

   dup2(fd, 0);
   dup2(fd, 1);
   system("/blugreen/homes/plank/bin/SUN4/pty -ne /usr/games/arithmetic");
   dup2(saved_stdin, 0);
   dup2(saved_stdout, 1);
   close(saved_stdin);
   close(saved_stdout);
   printf("client connection %d finished\n", fd);
}

