#include #include #include #include #include #include #include #include #include #include #include #include #include #include #define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0])) static inline void msleep(unsigned long ms); static inline void print_usage(char *progname); int socket_server_init(char *listen_ip, int listen_port); int main(int argc, char **argv) { int listenfd, connfd; int serv_port = 0; int daemon_run = 0; char *progname = NULL; int opt; fd_set rdset; int rv; int i, j; int found; int maxfd=0; char buf[1024]; int fds_array[1024]; struct option long_options[] = { {"daemon", no_argument, NULL, 'b'}, {"port", required_argument, NULL, 'p'}, {"help", no_argument, NULL, 'h'}, {NULL, 0, NULL, 0} }; progname = basename(argv[0]); /* Parser the command line parameters */ while ((opt = getopt_long(argc, argv, "bp:h", long_options, NULL)) != -1) { switch (opt) { case 'b': daemon_run=1; break; case 'p': serv_port = atoi(optarg); break; case 'h': /* Get help information */ print_usage(progname); return EXIT_SUCCESS; default: break; } } if( !serv_port ) { print_usage(progname); return -1; } if( (listenfd=socket_server_init(NULL, serv_port)) < 0 ) { printf("ERROR: %s server listen on port %d failure\n", argv[0],serv_port); return -2; } printf("%s server start to listen on port %d\n", argv[0],serv_port); /* set program running on background */ if( daemon_run ) { daemon(0, 0); } for(i=0; imaxfd ? fds_array[i] : maxfd; FD_SET(fds_array[i], &rdset); } /* program will blocked here */ rv = select(maxfd+1, &rdset, NULL, NULL, NULL); if(rv < 0) { printf("select failure: %s\n", strerror(errno)); break; } else if(rv == 0) { printf("select get timeout\n"); continue; } /* listen socket get event means new client start connect now */ if ( FD_ISSET(listenfd, &rdset) ) { if( (connfd=accept(listenfd, (struct sockaddr *)NULL, NULL)) < 0) { printf("accept new client failure: %s\n", strerror(errno)); continue; } found = 0; for(i=0; i