socket_server.c

Go to the documentation of this file.
00001 #include <string.h>
00002 #include <sys/types.h>
00003 #include <unistd.h>
00004 
00005 #include "proxylib.h"
00006 #include "echo.h"
00007 
00008 int ns_errno;
00009 
00010 int main(int argc, char **argv)
00011 {
00012   int listenfd, connfd;
00013   pid_t childpid;
00014   short port;
00015   socklen_t clilen;
00016   struct sockaddr_in cliaddr, servaddr;
00017   void sig_chld(int);
00018 
00019   if (argc == 2)
00020     port = atoi(argv[1]);
00021   else
00022     port = DEFAULT_PORT;
00023 
00024   listenfd = socket(AF_INET, SOCK_STREAM, 0);
00025 
00026   memset(&servaddr, 0x0, sizeof(servaddr));
00027   servaddr.sin_family = AF_INET;
00028   servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
00029   servaddr.sin_port = htons(port);
00030 
00031   bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr));
00032 
00033   listen(listenfd, 20);
00034 
00035   printf("Server listening on port %d\n", ntohs(servaddr.sin_port));
00036 
00037   signal(SIGCHLD, sig_chld);    /* must call waitpid() */
00038 
00039   for (;;) {
00040     clilen = sizeof(cliaddr);
00041     if ((connfd = accept(listenfd, (struct sockaddr *) &cliaddr, &clilen)) < 0) {
00042       if (errno == EINTR)
00043     continue;       /* back to for() */
00044       else {
00045     perror("accept error");
00046     exit(-1);
00047       }
00048     }
00049 
00050     if ((childpid = fork()) == 0) { /* child process */
00051       close(listenfd);      /* close listening socket */
00052       str_echo(connfd);     /* process the request */
00053       exit(0);
00054     }
00055     close(connfd);      /* parent closes connected socket */
00056   }
00057 }
00058 
00059 void sig_chld(int signo)
00060 {
00061   pid_t pid;
00062   int stat;
00063 
00064   while ((pid = waitpid(-1, &stat, WNOHANG)) > 0)
00065     printf("child %d terminated\n", (int)pid);
00066   return;
00067 }
00068 
00069 void str_echo(int sockfd)
00070 {
00071   ssize_t n;
00072   char line[MAXLINE];
00073 
00074   for (;;) {
00075     if ((n = Readline(sockfd, line, MAXLINE)) == 0)
00076       return;           /* connection closed by other end */
00077 
00078     Writen(sockfd, line, n);
00079   }
00080 }