-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathaccept_client_thread_epoll.c
73 lines (62 loc) · 1.98 KB
/
accept_client_thread_epoll.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
*
* @brief Accept client connections with pthread and epoll
*
*/
#include <arpa/inet.h> // for inet_ntoa()
#include <errno.h> // for errno
#include <netdb.h> // for getaddrinfo() and getservbyname
#include <pthread.h> // for pthread_create()
#include <signal.h> // for sigaction
#include <stdio.h> // for fprintf()
#include <stdlib.h> // for exit()
#include <string.h> // for strlen()
#include <sys/epoll.h> // for epoll
#include <sys/wait.h> // for waitpid
#include <unistd.h> // for close()
#include "../lib/die/die.h"
#include "../lib/logger/logger.h"
#include "accept_client_epoll.h"
#include "accept_client_thread_epoll.h"
#include "queue_connections.h"
#include "server.h"
struct threadData {
pthread_t thread;
int socketFd;
int epollFd;
};
void acceptClientsThreadEpoll(int socketServerFd) {
int nThreads = sysconf(_SC_NPROCESSORS_ONLN);
if (nThreads < 0) {
die("sysconf nº processors failed");
}
struct threadData threads[nThreads];
int epollFd = epoll_create1(0);
if (epollFd < 0) {
die("epoll_create failed");
}
addEpollClient(epollFd, socketServerFd, 0);
// create threads
int i;
for (i = 0; i < nThreads; i++) {
threads[i].socketFd = socketServerFd;
threads[i].epollFd = epollFd;
pthread_create(&threads[i].thread, NULL, workThreadEpoll, (void *)&threads[i]);
pthread_detach(threads[i].thread);
}
// We wait until we obtain the SIGINT signal
while (!sigintReceived) {
sleep(1);
}
// send a signal to exit the epoll loop and free any memory allocated
for (i = 0; i < nThreads; i++) {
pthread_kill(threads[i].thread, SIGINT);
// pthread_cancel(threads[i].thread);
}
usleep(100000); // time for threads to finish
}
void *workThreadEpoll(void *threadDataArg) {
struct threadData *threadData = (struct threadData *)threadDataArg;
handleEpoll(threadData->socketFd, threadData->epollFd);
return NULL;
}