#include #include #include #include #include #include #include void wait_for_child(int signum){ int exit_status; wait(&exit_status); printf("Child exited with status %d\n", exit_status); } int main(int argc, char ** argv){ // Install signal handler struct sigaction sa; sa.sa_handler = wait_for_child; sigaction(SIGCHLD, &sa, 0); // Network part struct sockaddr_in sad; sad.sin_port = htons(5141); sad.sin_addr.s_addr = INADDR_ANY; sad.sin_family = AF_INET; int skt = socket(AF_INET, SOCK_STREAM, 0); bind(skt, (struct sockaddr *)(&sad), sizeof(struct sockaddr_in)); listen(skt, 5); int client_fd; int usecount = 0; for(;;){ client_fd = accept(skt, 0, 0); if(client_fd < 3){ printf("Accept returned %d\n", client_fd); continue; } pid_t pid = fork(); if(pid){ // parent printf("Accepted a connection\n"); } else { // child inherits file descriptors that are open // This will replace our child with the wumpus game dup2(client_fd, 1); dup2(client_fd, 0); execl("/bin/sh", "sh", "-c", "wump", 0); // If wumpus runs, this next line will NEVER happen! printf("Couldn't start wumpus!\n"); } close(client_fd); // Connection doesn't close until BOTH parent and child have done this! } return 0; }