add poll to handle user input and web requests at the same time

This commit is contained in:
Nayan
2025-05-06 16:05:06 -04:00
parent d5a8e17f60
commit ff817b899b

View File

@@ -1,9 +1,12 @@
#include <netinet/in.h> #include <netinet/in.h>
#include <poll.h>
#include <pthread.h> #include <pthread.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <sys/socket.h> #include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include "client_handler.h" #include "client_handler.h"
@@ -18,7 +21,6 @@ int main(int argc, char **argv) {
} }
// Socket address config // Socket address config
server_addr.sin_family = AF_INET; server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY; server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(8080); server_addr.sin_port = htons(8080);
@@ -36,19 +38,47 @@ int main(int argc, char **argv) {
exit(1); exit(1);
} }
// Set up poll to monitor stdin and server
struct pollfd fds[2];
fds[0].fd = STDIN_FILENO;
fds[0].events = POLLIN;
fds[1].fd = server;
fds[1].events = POLLIN;
// Main loop
while (1) { while (1) {
struct sockaddr_in client_addr; int ret = poll(fds, 2, 0);
socklen_t client_len = sizeof(client_addr); if (ret > 0) {
int *client = malloc(sizeof(int)); // Check if stdin has data
if (fds[0].revents & POLLIN) {
char c;
read(STDIN_FILENO, &c, 1);
if (c == 'q') {
close(server);
printf("Server closed\n");
break;
}
}
*client = accept(server, (struct sockaddr *)&client_addr, &client_len); // Check if server has data
if (client < 0) { if (fds[1].revents & POLLIN) {
perror("Failed to accept client"); struct sockaddr_in client_addr;
continue; socklen_t client_len = sizeof(client_addr);
int *client = malloc(sizeof(int));
*client = accept(server, (struct sockaddr *)&client_addr,
&client_len);
if (client < 0) {
perror("Failed to accept client");
continue;
}
pthread_t thread;
pthread_create(&thread, NULL, client_handler, (void *)client);
pthread_detach(thread);
}
} }
pthread_t thread;
pthread_create(&thread, NULL, client_handler, (void *)client);
pthread_detach(thread);
} }
return 0;
} }