#include #include #include #include #include #include #include int main( int argc, char *argv[]) { int sockfd, epollfd, acceptfd, portno; struct epoll_event event = {EPOLLIN, NULL}, gotevent; char buffer[256]; struct sockaddr_in serv_addr; int n; volatile pid_t pid; printf("main PID %d\n", getpid()); memset((char *) &serv_addr, 0, sizeof(serv_addr)); portno = 5555; serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(portno); if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) return printf("socket() failed: %m\n"); int optval = 1; if ((setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval))) < 0) return printf("setsockopt() failed: %m"); if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) return printf("bind() failed: %m\n"); if (listen(sockfd, SOMAXCONN) < 0) return printf("listen() failed: %m\n"); if ((epollfd = epoll_create1(0)) < 0) return printf("epoll_create1() failed: %m\n"); if (epoll_ctl(epollfd, EPOLL_CTL_ADD, sockfd, &event) < 0) return printf("epoll_ctl() failed: %m\n"); while (1) { if (epoll_wait(epollfd, &gotevent, 1, -1) != 1) return printf("epoll_wait() failed: %m\n"); pid = fork(); if (pid == 0) { printf("PID %d started\n", getpid()); while(1) { struct sockaddr_in cli_addr; socklen_t cli_size = sizeof cli_addr; if ((acceptfd = accept(sockfd, (struct sockaddr *)&cli_addr, &cli_size)) < 0) { printf("PID %d accept() failed: %m\n", getpid()); sleep(60); return 1; } printf("PID %d accept()ed connection\n", getpid()); if (close(acceptfd) < 0) return printf("close() failed: %m\n"); } } else if (pid > 0) close(sockfd); } }