#include #include #include #include #include #include #include #include #include #include #include void* call_wait_in_loop(void* p){ pid_t pid; while(1){ pid = wait(0); if(pid == -1){ sleep(1); continue; } printf("Called wait for pid %d\n", pid); } return 0; } int main(int argc, char ** argv){ struct sockaddr_in sad; sad.sin_port = htons(5102); sad.sin_addr.s_addr = INADDR_ANY; sad.sin_family = AF_INET; int skt = socket(AF_INET, SOCK_STREAM, 0); // Step 1 if(skt == -1){ perror("socket"); return 1; } if( bind(skt, (struct sockaddr *)(&sad), sizeof(struct sockaddr_in)) ){ // step 2 perror("bind"); return 1; } if( listen(skt, 5) ){ // step 3 perror("listen"); return 1; } int client_fd; struct sockaddr_in client_address; socklen_t address_size = sizeof(struct sockaddr_in); pthread_t thread; pthread_create(&thread, 0, call_wait_in_loop, 0); while(1){ client_fd = accept(skt, (struct sockaddr *)(&client_address), &address_size); // step 4 fprintf(stderr, "Connection made from address %s\n", inet_ntoa(client_address.sin_addr)); // Let the client play wumpus! pid_t pid = fork(); if(!pid){ // We're the child dup2(client_fd, 0); dup2(client_fd, 1); printf("This is a printf from our server\n"); system("wump"); const char* message = "The user is disconnecting now\n"; write(2, message, strlen(message)); close(client_fd); break; } } // We're below an infinate loop, so this can't actually run pthread_join(thread, 0); return 0; }