-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
81 lines (61 loc) · 1.71 KB
/
main.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
74
75
76
77
78
79
80
81
#include <signal.h>
#include <stdlib.h>
#include "ip.h"
#include "logger.h"
#include "worker.h"
#if SCANNER == HTTP
#include "scanners/http.h"
#elif SCANNER == MINECRAFT
#include "scanners/minecraft.h"
#endif
void new_threadpool(pthread_t* threads, WorkerArgs* args);
void join_threads(pthread_t* threads);
void signal_handler(int sig);
int* run;
int main() {
log_level_from_env();
// Handle signals.
run = malloc(sizeof(int));
*run = 1;
signal(SIGINT, signal_handler);
WorkerArgs* args = malloc(sizeof(WorkerArgs));
args->queue = new_queue();
args->scanner = set_scanner();
init_db_pool();
// Create a pool of threads.
pthread_t threads[THREADS];
new_threadpool(threads, args);
// Start generating IPs and sending them to the queue.
generate_ips(args->queue, run);
INFO("MAIN", "Setting 'done' flag in queue");
// Signal that no more tasks will be added to the queue.
signal_done(args->queue);
join_threads(threads);
INFO("MAIN", "All tasks completed, cleaning up");
free_db_pool();
free_queue(args->queue);
free(args);
free(run);
return 0;
}
void new_threadpool(pthread_t* threads, WorkerArgs* args) {
INFO("THREAD", "Creating %d threads", THREADS);
for (int i = 0; i < THREADS; i++) {
int err = pthread_create(&threads[i], NULL, thread_worker, args);
if (err) {
FATAL("THREAD", "Creating thread ID '%d'", i);
}
threads[i] = threads[i];
}
}
void join_threads(pthread_t* threads) {
for (int i = 0; i < THREADS; i++) {
INFO("MAIN", "Waiting for thread '%d'", i);
pthread_join(threads[i], NULL);
INFO("MAIN", "Joined thread '%d'", i);
}
}
void signal_handler(int sig) {
INFO("MAIN", "Signal '%d' received, exiting", sig);
*run = 0;
}