int main(int argc, char **argv) { int r; progname = argv[0]; opts(argc, argv); job_init(); prot_init(); r = make_server_socket(host_addr, port); if (r == -1) twarnx("make_server_socket()"), exit(111); if (user) su(user); if (detach) daemonize(); event_init(); set_sig_handlers(); nudge_fd_limit(); unbrake((evh) h_accept); event_dispatch(); twarnx("got here for some reason"); return 0; }
static void accept_thread(void *arg) { int fd; int new_fd; int port; socklen_t addrlen; struct sockaddr addr; long smsbox_thread_id; port = *(int *) arg; fd = make_server_socket(port, NULL); if (fd == -1) panic(0, "Couldn't create SMPP listen port."); smsbox_thread_id = -1; for (;;) { if (gwthread_pollfd(fd, POLLIN, -1.0) != POLLIN) break; addrlen = sizeof(addr); new_fd = accept(fd, &addr, &addrlen); if (start_time == (time_t) -1) time(&start_time); gwthread_create(receive_smpp_thread, esme_create(conn_wrap_fd(new_fd, 0))); if (smsbox_thread_id == -1) smsbox_thread_id = gwthread_create(smsbox_thread, NULL); } debug("test.smpp", 0, "%s terminates.", __func__); }
main(int ac, char *av[]) { int sock, fd; int *fdptr; pthread_t worker; pthread_attr_t attr; void *handle_call(void *); if ( ac == 1 ){ fprintf(stderr,"usage: tws portnum\n"); exit(1); } sock = make_server_socket( atoi(av[1]) ); if ( sock == -1 ) { perror("making socket"); exit(2); } setup(&attr); /* main loop here: take call, handle call in new thread */ while(1){ fd = accept( sock, NULL, NULL ); server_requests++; fdptr = malloc(sizeof(int)); *fdptr = fd; pthread_create(&worker,&attr,handle_call,fdptr); } }
main(int ac, char *av[]) { int sock, fd; FILE *fpin; char request[BUFSIZ]; if ( ac == 1 ){ fprintf(stderr,"usage: ws portnum\n"); exit(1); } sock = make_server_socket( atoi(av[1]) ); if ( sock == -1 ) exit(2); while(1){ fd = accept( sock, NULL, NULL ); fpin = fdopen(fd, "r" ); fgets(request,BUFSIZ,fpin); printf("got a call: request = %s", request); read_til_crnl(fpin); process_rq(request, fd); fclose(fpin); } }
main(int ac, char *av[]) { int sock, fd; FILE *fpin; char request[BUFSIZ]; if ( ac == 1 ) { fprintf(stderr,"usage: ws portnum\n"); exit(1); } sock = make_server_socket( atoi(av[1]) ); if ( sock == -1 ) exit(2); /* main loop here */ while(1) { /* take a call and buffer it */ fd = accept( sock, NULL, NULL ); fpin = fdopen(fd, "r" ); /* read request */ fgets(request,BUFSIZ,fpin); printf("got a call: request = %s", request); read_til_crnl(fpin); /* do what client asks */ process_rq(request, fd); fclose(fpin); } }
static int wait_for_client(int port) { struct sockaddr_in sin; socklen_t addrlen; int listenfd; int clientfd; Octstr *addr; listenfd = make_server_socket(port, NULL); if (listenfd < 0) { fprintf(stderr, "%s: failed to open socket at port %d\n", progname, port); exit(1); } do { addrlen = sizeof(sin); clientfd = accept(listenfd, (struct sockaddr *)&sin, &addrlen); if (clientfd < 0) { error(errno, "failed to accept new connection"); } } while (clientfd < 0); if (socket_set_blocking(clientfd, 0) < 0) { panic(0, "failed to make client socket nonblocking"); } addr = gw_netaddr_to_octstr(AF_INET, &sin.sin_addr); info(0, "Accepted client from %s:%d", octstr_get_cstr(addr), ntohs(sin.sin_port)); octstr_destroy(addr); close(listenfd); return clientfd; }
int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "usage: ./webserv portnum\n"); exit(EXIT_FAILURE); } int sock_id = make_server_socket(atoi(argv[1])); int sock_fd; char request[BUFSIZ]; FILE *sock_fp; while (true) { // 循环中自然可以多次接收命令 sock_fd = accept(sock_id, NULL, NULL); sock_fp = fdopen(sock_fd, "r"); fgets(request, BUFSIZ, sock_fp); printf("got a call: request = %s\n", request); // sock_fp 和 sock_fd 的位置就是同一个,所以必须处理掉 sock_fp 的输出 char buf[BUFSIZ]; while (fgets(buf, BUFSIZ, sock_fp) != NULL && strcmp(buf, "\r\n") != 0) ; process_rq(request, sock_fd); fclose(sock_fp); } return EXIT_SUCCESS; }
static void sqlboxc_run(void *arg) { int fd; int port; /* we will use one thread for SQL sms injections */ gwthread_create(sql_to_bearerbox, NULL); port = (int)arg; fd = make_server_socket(port, NULL); /* XXX add interface_name if required */ if (fd < 0) { panic(0, "Could not open sqlbox port %d", port); } /* * infinitely wait for new connections; * to shut down the system, SIGTERM is send and then * select drops with error, so we can check the status */ wait_for_connections(fd, run_sqlbox, NULL); /* close listen socket */ close(fd); }
static int ois_open_listener(SMSCenter *smsc) { SAY(2, "ois_open_listener"); smsc->ois_listening_socket = make_server_socket(smsc->receive_port, NULL); /* XXX add interface_name if required */ if (smsc->ois_listening_socket < 0) { goto error; } if (socket_set_blocking(smsc->ois_listening_socket, 0) < 0) { ois_close(smsc); goto error; } smsc->ois_flags &= ~OIS_FLAG_ERROR; smsc->ois_flags &= ~OIS_FLAG_NOBANNER; smsc->ois_alive2 = time(&smsc->ois_alive); SAY2(2, "ois_open_listener fd=%d", smsc->ois_listening_socket); return 0; error: error(0, "ois_open_listener: failed to open listening socket"); return -1; }
static void smsboxc_run(void *arg) { int fd; int port; gwlist_add_producer(flow_threads); gwthread_wakeup(MAIN_THREAD_ID); port = (int) *((long *)arg); fd = make_server_socket(port, NULL); /* XXX add interface_name if required */ if (fd < 0) { panic(0, "Could not open smsbox port %d", port); } /* * infinitely wait for new connections; * to shut down the system, SIGTERM is send and then * select drops with error, so we can check the status */ wait_for_connections(fd, run_smsbox, incoming_sms, smsbox_port_ssl); gwlist_remove_producer(smsbox_list); /* continue avalanche */ gwlist_remove_producer(outgoing_sms); /* all connections do the same, so that all must remove() before it * is completely over */ while(gwlist_wait_until_nonempty(smsbox_list) == 1) gwthread_sleep(1.0); /* close listen socket */ close(fd); gwthread_wakeup(sms_dequeue_thread); gwthread_join(sms_dequeue_thread); gwlist_destroy(smsbox_list, NULL); smsbox_list = NULL; gw_rwlock_destroy(smsbox_list_rwlock); smsbox_list_rwlock = NULL; /* destroy things related to smsbox routing */ dict_destroy(smsbox_by_id); smsbox_by_id = NULL; dict_destroy(smsbox_by_smsc); smsbox_by_smsc = NULL; dict_destroy(smsbox_by_receiver); smsbox_by_receiver = NULL; dict_destroy(smsbox_by_smsc_receiver); smsbox_by_smsc_receiver = NULL; gwlist_remove_producer(flow_threads); }
int main(int argc, char **argv) { int r, l; struct event_base *ev_base; struct job binlog_jobs = {}; progname = argv[0]; opts(argc, argv); if (detach && binlog_dir) { if (binlog_dir[0] != '/') { warnx("The -b option requires an absolute path when used with -d."); usage("Path is not absolute", binlog_dir); } } job_init(); prot_init(); /* We want to make sure that only one beanstalkd tries to use the binlog * directory at a time. So acquire a lock now and never release it. */ if (binlog_dir) { r = binlog_lock(); if (!r) twarnx("failed to lock binlog dir %s", binlog_dir), exit(10); } r = make_server_socket(host_addr, port); if (r == -1) twarnx("make_server_socket()"), exit(111); l = r; if (user) su(user); ev_base = event_init(); set_sig_handlers(); nudge_fd_limit(); r = listen(l, 1024); if (r == -1) twarn("listen()"); accept_handler = (evh)h_accept; unbrake(); binlog_jobs.prev = binlog_jobs.next = &binlog_jobs; binlog_init(&binlog_jobs); prot_replay_binlog(&binlog_jobs); if (detach) { daemonize(); event_reinit(ev_base); } event_dispatch(); twarnx("event_dispatch error"); binlog_shutdown(); return 0; }
main() { int sock, fd; sock = make_server_socket( PORTNUM ); if ( sock == -1 ) oops( "make_server_socket" ); while( ( fd = accept(sock,NULL,NULL) ) != -1 ) { process_request(fd); close(fd); } }
static int __init s_init (void) { int ret; printk (KERN_INFO "Socket test module\n"); ret = make_server_socket (); if (ret) { printk (KERN_INFO "Server socket creation failed: %d\n", ret); return ret; } return 0; }
int main(int argc, char *argv[]) { if (argc < 3) { write_(STDOUT_FILENO, "Usage:\n filesender port file\n", 32); return 0; } struct sigaction sa; bzero(&sa, sizeof(sa)); sa.sa_handler = SIG_IGN; sa.sa_flags = SA_RESTART; CATCH_IO(sigaction(SIGCHLD, &sa, NULL)); CATCH_IO(access(argv[2], R_OK | F_OK)); int sock; CATCH_IO(sock = make_server_socket(argv[1])); CATCH_IO(listen(sock, 1)); struct sockaddr_in client; socklen_t len = sizeof(client); while(1) { int remote, pid; CATCH_IO(remote = accept(sock, (struct sockaddr*) &client, &len)); CATCH_IO(pid = fork()); if (pid == 0) { int file; CATCH_IO(file = open(argv[2], O_RDONLY)); int s = cat(file, remote); int exit_status = 0; if (s == -1) { perror("Error while sending file"); exit_status = 1; } close(remote); close(file); _exit(exit_status); } CATCH_IO(close(remote)); } CATCH_IO(close(sock)); return 0; }
static Connection *start_wapbox(void) { int wap_socket; int wapbox; wap_socket = make_server_socket(wapbox_port, NULL); if (wap_socket < 0) panic(0, "Couldn't make wapbox port\n"); wapbox = accept(wap_socket, NULL, NULL); if (wapbox < 0) panic(errno, "Wapbox could not connect\n"); close(wap_socket); return conn_wrap_fd(wapbox, 0); }
int main(void) { pthread_t worker; pthread_attr_t attrt; pthread_attr_init(&attrt); pthread_attr_setdetachstate(&attrt,PTHREAD_CREATE_DETACHED); int sockfd,sockcnfd; FILE *sockfp; struct sockaddr_in clsockaddr; sockfd=make_server_socket(SERVER_PORT,SERVER_LISNUM); while(1){ sockcnfd=server_accept(sockfd,&clsockaddr); pthread_create(&worker,&attrt,process_accept,&sockcnfd); } return 0; }
static int cgw_open_listening_socket(SMSCConn *conn, PrivData *privdata) { int s; if ((s = make_server_socket(privdata->rport, (conn->our_host ? octstr_get_cstr(conn->our_host) : NULL))) == -1) { error(0, "smsc_cgw: could not create listening socket in port %d", privdata->rport); return -1; } if (socket_set_blocking(s, 0) == -1) { error(0, "smsc_cgw: couldn't make listening socket port %d non-blocking", privdata->rport); close(s); return -1; } privdata->listening_socket = s; return 0; }
void server_test(as_lua_pconf_t *cnf) { as_cnf_return_t ret = lpconf_get_pconf_value(cnf, 1, "tcp_port"); int sock; sock = make_server_socket(ret.val.i); if (sock < 0) { exit(EXIT_FAILURE); } set_non_block(sock); if (listen(sock, 500) < 0) { perror("listen"); exit(EXIT_FAILURE); } // select_server(sock); // epoll_server(sock); test_worker_process(sock, cnf); close(sock); }
int main(int argc, char **argv) { int r; Srv s = {}; s.wal.filesz = Filesizedef; struct job list = {}; progname = argv[0]; opts(argc, argv, &s.wal); if (verbose) { printf("pid %d\n", getpid()); } r = make_server_socket(host_addr, port); if (r == -1) twarnx("make_server_socket()"), exit(111); s.sock.fd = r; prot_init(); if (user) su(user); set_sig_handlers(); if (s.wal.use) { // We want to make sure that only one beanstalkd tries // to use the wal directory at a time. So acquire a lock // now and never release it. if (!waldirlock(&s.wal)) { twarnx("failed to lock wal dir %s", s.wal.dir); exit(10); } list.prev = list.next = &list; walinit(&s.wal, &list); prot_replay(&s, &list); } srv(&s); return 0; }
main() { int sock, fd; void child_waiter(); signal( SIGCHLD, SIG_DFL ); sock = make_server_socket( PORTNUM ); if ( sock == -1 ) oops( "make_server_socket" ); while( 1 ) { fd = accept(sock,NULL,NULL ); if ( fd == -1 ){ if ( errno == EINTR ) continue; break; } process_request(fd); close(fd); } }
void main(int argc, char * argv[]) { int server_socket; int acc_socket; int size; struct sockaddr_in user_socket; size = sizeof(struct sockaddr_in); if((server_socket = make_server_socket())==-1){ printf("Server error!\n"); exit(0); } pthread_t tid[50]; int i = 0; for(i = 0;i < 50; i++) pthread_create(&tid[i],NULL,thread,(void *)server_socket); for(i = 0;i < 50; i++) pthread_join(tid[i],NULL); }
void server() { ctx_t *ctx = make_ctx(SIZE); ctx->sock = make_server_socket(); ctx->who = SERVER; /* both delay */ ctx->mili = unit; do_server_run(ctx); /* server delay */ do_server_run(ctx); /* client delay */ ctx->mili = 0; do_server_run(ctx); shutdown(ctx->sock, 0); free_ctx(ctx); return; }
static void wapboxc_run(void *arg) { int fd, port; gwlist_add_producer(flow_threads); gwthread_wakeup(MAIN_THREAD_ID); port = (int) *((long*)arg); fd = make_server_socket(port, NULL); /* XXX add interface_name if required */ if (fd < 0) { panic(0, "Could not open wapbox port %d", port); } wait_for_connections(fd, run_wapbox, incoming_wdp, wapbox_port_ssl); /* continue avalanche */ gwlist_remove_producer(outgoing_wdp); /* wait for all connections to die and then remove list */ while(gwlist_wait_until_nonempty(wapbox_list) == 1) gwthread_sleep(1.0); /* wait for wdp_to_wapboxes to exit */ while(gwlist_consume(wapbox_list)!=NULL) ; /* close listen socket */ close(fd); gwlist_destroy(wapbox_list, NULL); wapbox_list = NULL; gwlist_remove_producer(flow_threads); }
static int __init verbs_init (void) { int res = 0; printk (KERN_INFO "Verbs test module\n"); if (!server_addr) res = make_server_socket (); if (res) { printk (KERN_INFO "Socket creation failed: %d\n", res); return -EINVAL; } /* register Subnet Administrator client` */ ib_sa_register_client(&verbs_sa_client); if (ib_register_client (&client)) { printk (KERN_WARNING "IB client registration failed. Is IB modules loaded?\n"); return -ENODEV; } return 0; }
int main(int argc, char *argv[]) { int sock; fd_set readfds; struct timeval tv; int result; lwm2m_context_t * lwm2mH = NULL; int i; connection_t * connList = NULL; int addressFamily = AF_INET6; int opt; const char * localPort = LWM2M_STANDARD_PORT_STR; command_desc_t commands[] = { {"list", "List registered clients.", NULL, prv_output_clients, NULL}, {"read", "Read from a client.", " read CLIENT# URI\r\n" " CLIENT#: client number as returned by command 'list'\r\n" " URI: uri to read such as /3, /3/0/2, /1024/11, /1024/0/1\r\n" "Result will be displayed asynchronously.", prv_read_client, NULL}, {"disc", "Discover resources of a client.", " disc CLIENT# URI\r\n" " CLIENT#: client number as returned by command 'list'\r\n" " URI: uri to discover such as /3, /3/0/2, /1024/11, /1024/0/1\r\n" "Result will be displayed asynchronously.", prv_discover_client, NULL}, {"write", "Write to a client.", " write CLIENT# URI DATA\r\n" " CLIENT#: client number as returned by command 'list'\r\n" " URI: uri to write to such as /3, /3/0/2, /1024/11, /1024/0/1\r\n" " DATA: data to write\r\n" "Result will be displayed asynchronously.", prv_write_client, NULL}, {"time", "Write time-related attributes to a client.", " time CLIENT# URI PMIN PMAX\r\n" " CLIENT#: client number as returned by command 'list'\r\n" " URI: uri to write attributes to such as /3, /3/0/2, /1024/11, /1024/0/1\r\n" " PMIN: Minimum period\r\n" " PMAX: Maximum period\r\n" "Result will be displayed asynchronously.", prv_time_client, NULL}, {"attr", "Write value-related attributes to a client.", " attr CLIENT# URI LT GT [STEP]\r\n" " CLIENT#: client number as returned by command 'list'\r\n" " URI: uri to write attributes to such as /3, /3/0/2, /1024/11, /1024/0/1\r\n" " LT: \"Less than\" value\r\n" " GT: \"Greater than\" value\r\n" " STEP: \"Step\" value\r\n" "Result will be displayed asynchronously.", prv_attr_client, NULL}, {"clear", "Clear attributes of a client.", " clear CLIENT# URI\r\n" " CLIENT#: client number as returned by command 'list'\r\n" " URI: uri to clear attributes of such as /3, /3/0/2, /1024/11, /1024/0/1\r\n" "Result will be displayed asynchronously.", prv_clear_client, NULL}, {"exec", "Execute a client resource.", " exec CLIENT# URI\r\n" " CLIENT#: client number as returned by command 'list'\r\n" " URI: uri of the resource to execute such as /3/0/2\r\n" "Result will be displayed asynchronously.", prv_exec_client, NULL}, {"del", "Delete a client Object instance.", " del CLIENT# URI\r\n" " CLIENT#: client number as returned by command 'list'\r\n" " URI: uri of the instance to delete such as /1024/11\r\n" "Result will be displayed asynchronously.", prv_delete_client, NULL}, {"create", "create an Object instance.", " create CLIENT# URI DATA\r\n" " CLIENT#: client number as returned by command 'list'\r\n" " URI: uri to which create the Object Instance such as /1024, /1024/45 \r\n" " DATA: data to initialize the new Object Instance (0-255 for object 1024) \r\n" "Result will be displayed asynchronously.", prv_create_client, NULL}, {"observe", "Observe from a client.", " observe CLIENT# URI\r\n" " CLIENT#: client number as returned by command 'list'\r\n" " URI: uri to observe such as /3, /3/0/2, /1024/11\r\n" "Result will be displayed asynchronously.", prv_observe_client, NULL}, {"cancel", "Cancel an observe.", " cancel CLIENT# URI\r\n" " CLIENT#: client number as returned by command 'list'\r\n" " URI: uri on which to cancel an observe such as /3, /3/0/2, /1024/11\r\n" "Result will be displayed asynchronously.", prv_cancel_client, NULL}, {"q", "Quit the server.", NULL, prv_quit, NULL}, COMMAND_END_LIST }; opt = 1; while (opt < argc) { if (argv[opt] == NULL || argv[opt][0] != '-' || argv[opt][2] != 0) { print_usage(); return 0; } switch (argv[opt][1]) { case '4': addressFamily = AF_INET; break; case 'l': opt++; if (opt >= argc) { print_usage(); return 0; } localPort = argv[opt]; break; default: print_usage(); return 0; } opt += 1; } sock = make_server_socket(atoi(LWM2M_STANDARD_PORT_STR)); if (sock < 0) { fprintf(stderr, "Error opening socket: %d\r\n", errno); return -1; } lwm2mH = lwm2m_init(NULL); if (NULL == lwm2mH) { fprintf(stderr, "lwm2m_init() failed\r\n"); return -1; } signal(SIGINT, handle_sigint); for (i = 0 ; commands[i].name != NULL ; i++) { commands[i].userData = (void *)lwm2mH; } fprintf(stdout, "> "); fflush(stdout); lwm2m_set_monitoring_callback(lwm2mH, prv_monitor_callback, lwm2mH); struct sockaddr_in clntAddr; unsigned int clntLen = sizeof(clntAddr); int clientSock = accept(sock, (struct sockaddr *) &clntAddr, &clntLen); if (clientSock < 0) { fprintf(stderr, "OOPS %d\n", errno); return -200; } while (0 == g_quit) { FD_ZERO(&readfds); FD_SET(clientSock, &readfds); FD_SET(STDIN_FILENO, &readfds); tv.tv_sec = 60; tv.tv_usec = 0; result = lwm2m_step(lwm2mH, &(tv.tv_sec)); if (result != 0) { fprintf(stderr, "lwm2m_step() failed: 0x%X\r\n", result); return -1; } result = select(FD_SETSIZE, &readfds, 0, 0, &tv); if ( result < 0 ) { if (errno != EINTR) { fprintf(stderr, "Error in select(): %d\r\n", errno); } } else if (result > 0) { uint8_t buffer[MAX_PACKET_SIZE]; int numBytes; if (FD_ISSET(clientSock, &readfds)) { numBytes = recv(clientSock, buffer, 2 /*uint16_t*/, 0); if (numBytes == -1) { fprintf(stderr, "Error in recvfrom(): %d\r\n", errno); } else { struct sockaddr_storage addr; socklen_t addrLen = sizeof(addr); uint32_t msgLength = parse_int(buffer, 2); printf("\tmsgLength: %d\n", msgLength); numBytes = 0; /* number of bytes read */ while (numBytes < msgLength) { numBytes += recvfrom(clientSock, &buffer[numBytes], msgLength - numBytes, 0, (struct sockaddr *) &addr, &addrLen); } printf("\trLength: %d\n", numBytes); char s[INET6_ADDRSTRLEN]; in_port_t port; connection_t * connP; s[0] = 0; if (AF_INET == addr.ss_family) { struct sockaddr_in *saddr = (struct sockaddr_in *)&addr; inet_ntop(saddr->sin_family, &saddr->sin_addr, s, INET_ADDRSTRLEN); port = saddr->sin_port; } else if (AF_INET6 == addr.ss_family) { struct sockaddr_in6 *saddr = (struct sockaddr_in6 *)&addr; inet_ntop(saddr->sin6_family, &saddr->sin6_addr, s, INET6_ADDRSTRLEN); port = saddr->sin6_port; } fprintf(stderr, "%d bytes received from [%s]:%hu\r\n", numBytes, s, ntohs(port)); output_buffer(stderr, buffer, numBytes, 0); connP = connection_find(connList, &addr, addrLen); if (connP == NULL) { connP = connection_new_incoming(connList, clientSock, (struct sockaddr *)&addr, addrLen); if (connP != NULL) { connList = connP; } } if (connP != NULL) { lwm2m_handle_packet(lwm2mH, buffer, numBytes, connP); } } } else if (FD_ISSET(STDIN_FILENO, &readfds)) { numBytes = read(STDIN_FILENO, buffer, MAX_PACKET_SIZE - 1); if (numBytes > 1) { buffer[numBytes] = 0; handle_command(commands, (char*)buffer); fprintf(stdout, "\r\n"); } if (g_quit == 0) { fprintf(stdout, "> "); fflush(stdout); } else { fprintf(stdout, "\r\n"); } } } } lwm2m_close(lwm2mH); close(clientSock); close(sock); connection_free(connList); #ifdef MEMORY_TRACE if (g_quit == 1) { trace_print(0, 1); } #endif return 0; }
inline std::unique_ptr<tcp_server_socket> make_server_socket( const ip_address& ip, std::uint16_t port, tcp_server_socket::wrapper w, bool freebind = false) { return make_server_socket(ip.str().c_str(), port, w, freebind); }
int main(int argc, char ** argv) { int listen_fd, epfd; int epoll_events_count; struct epoll_event ev, events[EPOLL_EVENTS_MAX]; struct sockaddr_in clientaddr; socklen_t addrlen; int i, serv_port; SAK_threadpool_t * tp_handler = NULL; #if DEBUG clock_t tstart; #endif if(argc != 2) { perror("usage: ./lotus <port>"); exit(-1); } serv_port = atoi(argv[1]); bzero(&clientaddr, sizeof(clientaddr)); addrlen = sizeof(struct sockaddr_in); /*********************** thread pool ***************************/ tp_handler = threadpool_create(THREADPOOL_THREADS); assert(tp_handler != NULL); printf("thread pool is created\n"); /************************** socket *****************************/ /* make server socket */ ERR2(listen_fd, make_server_socket(serv_port)); printf("web server socket is made\n"); /**************************** epoll ****************************/ /* create epoll */ ERR2(epfd, epoll_create(EPOLL_SIZE)); ev.data.fd = listen_fd; ev.events = EPOLLIN|EPOLLET; ERR(set_nonblock(listen_fd)); /* add listen_fd to epoll */ ERR(epoll_ctl(epfd, EPOLL_CTL_ADD, listen_fd, &ev)); printf("epoll module is created\n"); /* ignore pipe broken signal */ signal(SIGPIPE, SIG_IGN); /************************* main ********************************/ for(;;) { /* wait for changes of fd set */ ERR2(epoll_events_count, epoll_wait(epfd, events, EPOLL_EVENTS_MAX, EPOLL_TIMEOUT)); #if DEBUG tstart = clock(); #endif for(i = 0; i < epoll_events_count; i++) { #if DEBUG printf("events[%d].data.fd == %d\n", i, events[i].data.fd); #endif if((events[i].events & EPOLLERR) || (events[i].events & EPOLLHUP) || (!(events[i].events & EPOLLIN))) { fprintf(stderr, "ERROR: epoll error\n"); close(events[i].data.fd); continue; } else if(events[i].data.fd == listen_fd) { #if DEBUG printf("Is listen_fd = %d\n", listen_fd); #endif /* a new connection is coming, we accept it and add the new connection fd to epoll set */ while(1) { int connect_fd; char clientaddr_buff[20] = {0}; connect_fd = accept(listen_fd, (struct sockaddr *)&clientaddr, &addrlen); if(connect_fd == -1) { if((errno == EAGAIN) || (errno == EWOULDBLOCK)) { /* We have process all incoming connection */ break; } else { perror("accept"); break; } } inet_ntop(AF_INET, &clientaddr.sin_addr, clientaddr_buff, sizeof(clientaddr_buff)), printf("Client [%s : %d] is connected\n", clientaddr_buff, ntohs(clientaddr.sin_port)); ERR(set_nonblock(connect_fd)); ev.data.fd = connect_fd; #if DEBUG printf("Get and put connect_fd = %d into epoll\n", connect_fd); #endif ev.events = EPOLLIN|EPOLLET; ERR(epoll_ctl(epfd, EPOLL_CTL_ADD, connect_fd, &ev)); } continue; } else { /* Can read */ /************************************************/ /* Put the task into thread pool's work queue */ /************************************************/ #if DEBUG printf("Is connect_fd = %d\n", events[i].data.fd); #endif threadpool_put(tp_handler, process_request, (void *)events[i].data.fd); request_count ++; printf("Has handle %d requests\n", request_count); //ERR(epoll_ctl(epfd, EPOLL_CTL_DEL, ev.data.fd, &ev)); } } #if DEBUG printf("Statistics: %d events handled at %2.f seconds(s)\n", epoll_events_count, (double)(clock() - tstart)/CLOCKS_PER_SEC); #endif } close(listen_fd); close(epfd); threadpool_destroy(tp_handler); return 0; }