-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
99 lines (83 loc) · 2.37 KB
/
main.cpp
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include "queue.h"
#include "util.h"
#include "http.h"
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <signal.h>
#include <iostream>
#include <errno.h>
#include <string>
#include <thread>
#define POOL_SIZE 128
class WorkerThread {
public:
WorkerThread(ThreadQueue<int>& q) : q_(q) {
}
WorkerThread(const WorkerThread& w) : q_(w.q_) {
}
void operator()() {
while (true) {
q_.Pop();
std::cout << "Got" << std::endl;
}
}
private:
ThreadQueue<int>& q_;
};
int main(int argc, char** argv) {
sigignore(SIGHUP);
Params params = ParseParams(argc, argv);
std::cout << "Host: " << params.host << std::endl;
std::cout << "Port: " << params.port << std::endl;
std::cout << "Dir: " << params.dir << std::endl;
Daemonize();
ThreadQueue<int> t_q;
// TODO(stash): why cannot pass WorkerThread here (copy constructor error)?
const std::string& dir = params.dir;
std::thread worker([&t_q, dir] ()
{
while (true) {
auto x = t_q.Pop();
RequestHandler(x, dir);
}
}
);
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
std::cout << "socket failed " << errno << std::endl;
close(sock);
exit(EXIT_FAILURE);
}
int enable = 1;
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0) {
std::cout << "setsockopt failed " << errno << std::endl;
exit(EXIT_FAILURE);
}
sockaddr_in sa;
sa.sin_family = AF_INET;
sa.sin_port = htons(params.port);
sa.sin_addr.s_addr = inet_addr(params.host.c_str());
if (-1 == bind(sock,(sockaddr*)&sa, sizeof(sockaddr_in))) {
std::cout << "bind() failed " << errno << std::endl;
close(sock);
exit(EXIT_FAILURE);
}
if (-1 == listen(sock, -1)) {
std::cout << "listen() failed " << errno << std::endl;
close(sock);
exit(EXIT_FAILURE);
}
while (true) {
std::cout << "Before accept" << std::endl;
auto accepted_sock = accept(sock, NULL, NULL);
if (-1 == accepted_sock) {
std::cout << "accept failed: " << errno << std::endl;
close(accepted_sock);
continue;
}
t_q.Push(accepted_sock);
}
worker.join();
}