about summary refs log tree commit diff
path: root/cptc.c
diff options
context:
space:
mode:
authorNakidai <nakidai@disroot.org>2024-09-28 16:09:14 +0300
committerNakidai <nakidai@disroot.org>2024-09-28 16:09:14 +0300
commitd3046284b23ca81be438c94e8f83b7e13e929d81 (patch)
tree541a2de8cf543eee4abd99e6916e3169672f8cea /cptc.c
parentffa61b7b6930fe4a08bb53ace07c2ee40a9cef43 (diff)
downloadcptc-d3046284b23ca81be438c94e8f83b7e13e929d81.tar.gz
cptc-d3046284b23ca81be438c94e8f83b7e13e929d81.zip
Make it multithreaded v1.0.0
And also add `int n` to the CPTC_requestHandler so it threads will not
conflict with each other with filenames
Diffstat (limited to 'cptc.c')
-rw-r--r--cptc.c32
1 files changed, 27 insertions, 5 deletions
diff --git a/cptc.c b/cptc.c
index 0396b71..1dafddc 100644
--- a/cptc.c
+++ b/cptc.c
@@ -1,11 +1,14 @@
 #include "cptc.h"
 
+#include <stdbool.h>
 #include <stdio.h>
 #include <stdlib.h>
 
 #include <sys/socket.h>
 #include <netinet/in.h>
 #include <arpa/inet.h>
+
+#include <pthread.h>
 #include <unistd.h>
 
 #include <curl/curl.h>
@@ -20,11 +23,30 @@
     } while (0)             \
 
 
+struct RequestHandlerArgs
+{
+    int fd;
+    int n;
+    bool accept;
+};
+
+static void *requestHandlerThread(struct RequestHandlerArgs *arg)
+{
+    int fd = arg->fd;
+    int n = arg->n;
+    arg->accept = true;
+    CPTC_requestHandler(fd, n);
+    close(fd);
+    pthread_exit(NULL);
+}
+
+
 void CPTC(const char *ip, in_port_t port)
 {
     struct sockaddr_in addr, peer;
     socklen_t peer_size;
     int fd, peerfd;
+    int n = 0;
 
     curl_easy_init();
 
@@ -56,10 +78,10 @@ void CPTC(const char *ip, in_port_t port)
         }
         printf("Connection from %s:%u!\n", inet_ntoa(peer.sin_addr), peer.sin_port);
 
-        /*
-         * TODO: Make it multithreaded
-         */
-        CPTC_requestHandler(peerfd);
-        close(peerfd);
+        pthread_t thread;
+        struct RequestHandlerArgs arg = {peerfd, n++, false};
+        pthread_create(&thread, NULL, (void *(*)(void *))requestHandlerThread, &arg);
+        pthread_detach(thread);
+        while (!arg.accept);
     }
 }