Defines | Functions | Variables

nse_server.c File Reference

#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include "echo.h"
#include "proxylib.h"
Include dependency graph for nse_server.c:

Go to the source code of this file.

Defines

#define DEFAULT_PORT   12345

Functions

int main (int argc, char **argv)
void sig_chld (int signo)
void str_echo (int sockfd)

Variables

int ns_errno

Define Documentation

#define DEFAULT_PORT   12345

Definition at line 10 of file nse_server.c.


Function Documentation

int main ( int  argc,
char **  argv 
)

Definition at line 12 of file nse_server.c.

{
  int listenfd, connfd;
  pid_t childpid;
  short port;
  socklen_t clilen;
  struct sockaddr_in cliaddr, servaddr;
  void sig_chld(int);

  if (argc == 2)
    port = atoi(argv[1]);
  else
    port = DEFAULT_PORT;

  proxy_init("nse.cfg");

  if ((listenfd = proxy_socket(AF_INET, SOCK_STREAM, 0)) < 0) {
    perror("Failed to create socket");
    exit(EXIT_FAILURE);
  }

  memset(&servaddr, 0x0, sizeof(servaddr));
  servaddr.sin_family = AF_INET;
  servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
  servaddr.sin_port = htons(port);

  if (proxy_bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) {
    perror("Failed to bind");
    exit(EXIT_FAILURE);
  }

  if (proxy_listen(listenfd, 20) < 0) {
    perror("Listen failed");
    exit(EXIT_FAILURE);
  }

  printf("Server listening on port %d\n", ntohs(servaddr.sin_port));

  signal(SIGCHLD, sig_chld);    /* must call waitpid() */

  for (;;) {
    clilen = sizeof(cliaddr);
    if ((connfd = proxy_accept(listenfd, (struct sockaddr *) &cliaddr, &clilen)) < 0) {
      if (errno == EINTR)
    continue;       /* back to for() */
      else {
    perror("accept error");
    exit(-1);
      }
    }

    if ((childpid = fork()) == 0) { /* child process */
      proxy_close(listenfd);    /* close listening socket */
      str_echo(connfd);     /* process the request */
      exit(0);
    }
    close(connfd);      /* parent closes connected socket */
  }
}

Here is the call graph for this function:

void sig_chld ( int  signo  ) 

Definition at line 72 of file nse_server.c.

{
  pid_t pid;
  int stat;

  while ((pid = waitpid(-1, &stat, WNOHANG)) > 0)
    printf("child %d terminated\n", (int)pid);
  return;
}

void str_echo ( int  sockfd  ) 

Definition at line 82 of file nse_server.c.

{
  ssize_t n;
  char line[MAXLINE];

  for (;;) {
    if ((n = Readline(sockfd, line, MAXLINE)) == 0)
      return;           /* connection closed by other end */

    Writen(sockfd, line, n);
  }
}

Here is the call graph for this function:


Variable Documentation

int ns_errno

Definition at line 8 of file nse_server.c.