CS360 Final Exam. Answer to Question 2

8 points

December 13, 1997

This is straight from the lecture notes. Something like the following will work (serving on port 7777):
#include "socketfun.h"

main()
{
  int sock, fd;

  sock = serve_socket("games.cs.utk.edu", 7777);
  
  while(1) {
    fd = accept_connection(sock);
    if (fork() != 0) {
      dup2(fd, 0);
      dup2(fd, 1);
      close(fd);
      close(sock);
      execlp("game", "game", NULL);
      perror("execlp");
      exit(1);
    } else {
      close(fd);
    }
  }
}
Note that this gets rid of zombies by having the parent process serve the connection while the child continues to serve other connections.

You can also get rid of zombies by something like:


#include "socketfun.h"

main()
{
  int sock, fd, dummy;

  sock = serve_socket("games.cs.utk.edu", 7777);

  while(1) {
    fd = accept_connection(sock);
    if (fork() == 0) {
      if (fork() == 0) {
        dup2(fd, 0);
        dup2(fd, 1);
        close(fd);
        close(sock);
        execlp("game", "game", NULL);
        perror("execlp");
        exit(1);
      } else {
        exit(0);
      }
    } else {
      close(fd);
      wait(&dummy);
    }
  }
}