Functions | Variables

socket_server.c File Reference

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

Go to the source code of this file.

Functions

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

Variables

int ns_errno

Function Documentation

int main ( int  argc,
char **  argv 
)

Definition at line 10 of file socket_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;

  listenfd = socket(AF_INET, SOCK_STREAM, 0);

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

  bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr));

  listen(listenfd, 20);

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

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

  for (;;) {
    clilen = sizeof(cliaddr);
    if ((connfd = 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 */
      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 59 of file socket_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 69 of file socket_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:

Here is the caller graph for this function:


Variable Documentation

int ns_errno

Definition at line 8 of file socket_server.c.