void wait_for_connections(uint16_t port, struct vehicle_list *vehicles) { int sockfd; struct accept_connection_data *data; pthread_attr_t t_attr; t_sigmask(SIGINT, SIG_UNBLOCK); sockfd = make_and_bind_socket(port, SOCK_STREAM); socket_listen(sockfd, 16); while(work) { data = (struct accept_connection_data*)malloc(sizeof(struct accept_connection_data)); if(data == NULL) error_exit("Memory allocation:"); data->fd = 0; data->vehicles = vehicles; while(work && (data->fd = accept(sockfd, NULL, NULL)) < 0) { if(errno == EINTR) continue; error_exit("Accepting connection:"); } t_sigmask(SIGINT, SIG_BLOCK); if(data->fd > 0) start_detached_thread(&data->mutex, &t_attr, &data->thread, accept_connection, data); else free(data); t_sigmask(SIGINT, SIG_UNBLOCK); } socket_close(sockfd); }
void init_signals() { _signal(SIGINT, sigint); _signal(SIGALRM, sigalarm); t_sigmask(SIGINT, SIG_BLOCK); t_sigmask(SIGALRM, SIG_BLOCK); }
void server_work(int listenfd, pthread_cond_t *cond, struct service *service, struct horse *horses, size_t horse_num) { pthread_t tid; int *iptr; struct sockaddr_in cliaddr; struct user *user; socklen_t clilen; // for signal handling t_sigmask(SIGINT, SIG_UNBLOCK); t_sigmask(SIGALRM, SIG_UNBLOCK); // set alarm for next run choose_run_horses(horses, horse_num, service); alarm(service->delay); while (work) { // accepting client, while there is no run if (!run) { clilen = sizeof(cliaddr); iptr = _malloc(sizeof(int)); *iptr = accept(listenfd, (struct sockaddr *)&cliaddr, &clilen); if (*iptr < 0) { if (errno == EINTR) continue; } if (run) { free(iptr); continue; } user = (struct user *)_malloc(sizeof(struct user)); user->sockfd = iptr; user->service = service; user->mnr = service->mnr; user->mhb = service->mhb; _pthread_create(&tid, NULL, client_thread, user); } else play(cond, service, horses, horse_num); } _close(listenfd); }
int main(int argc, char **argv) { int port, timestep; if(argc != 3) usage(argv[0]); port = atoi(argv[1]); timestep = atoi(argv[2]); if(port <= 0 || timestep <= 0) usage(argv[0]); if(sethandler(SIG_IGN, SIGPIPE)) error_exit("Setting SIGPIPE handler:"); if(sethandler(sigint_handler, SIGINT)) error_exit("Setting SIGINT handler:"); t_sigmask(SIGINT, SIG_BLOCK); server_work((uint16_t)port, timestep); return EXIT_SUCCESS; }