2 #include <sys/socket.h>
8 #include <boost/thread.hpp>
12 #include "main_thread.h"
13 #include "config_thread.h"
15 MAIN_THREAD::MAIN_THREAD(ADMINS * a, TARIFFS * t, USERS * u, const SETTINGS * s)
27 MAIN_THREAD::~MAIN_THREAD()
31 void MAIN_THREAD::operator() ()
39 if (WaitConnection()) {
46 counter = counter % 10; // Every 5 sec
52 bool MAIN_THREAD::InitNetwork()
54 struct sockaddr_in listenAddr;
56 sd = socket(AF_INET, SOCK_STREAM, 0);
59 printfd(__FILE__, "MAIN_THREAD::InitNetwork() Socket creation failed: '%s'\n", strerror(errno));
63 listenAddr.sin_family = AF_INET;
64 listenAddr.sin_port = htons(port);
65 listenAddr.sin_addr.s_addr = INADDR_ANY;
67 if (bind(sd, (struct sockaddr*)&listenAddr, sizeof(listenAddr)) < 0) {
68 printfd(__FILE__, "MAIN_THREAD::InitNetwork() Bind failed: '%s'\n", strerror(errno));
72 if(listen(sd, 8) < 0) {
73 printfd(__FILE__, "MAIN_THREAD::InitNetwork() Error starting to listen: '%s'\n", strerror(errno));
80 bool MAIN_THREAD::WaitConnection()
86 /* Wait up to five seconds. */
91 int res = select(sd + 1, &rfds, NULL, NULL, &tv);
92 /* Don't rely on the value of tv now! */
95 printfd(__FILE__, "MAIN_THREAD::WaitConnection() Select failed: '%s'\n", strerror(errno));
99 if (res && FD_ISSET(sd, &rfds)) {
107 void MAIN_THREAD::AcceptConnection()
109 if (connections.size() >= maxConnections) {
111 if (connections.size() >= maxConnections) {
116 struct sockaddr_in remoteAddr;
117 socklen_t len = sizeof(remoteAddr);
118 int newSD = accept(sd, (struct sockaddr *)&remoteAddr, &len);
121 printfd(__FILE__, "MAIN_THREAD::AcceptConnection() Accept failed: '%s'\n", strerror(errno));
125 CONFIG_THREAD ct(admins, tariffs, users, settings);
126 ct.SetConnection(newSD, remoteAddr);
128 connections.push_back(ct);
129 boost::thread thread(boost::ref(connections.back()));
133 void MAIN_THREAD::CleanupThreads()
135 connections.remove_if(
136 std::mem_fun_ref(&CONFIG_THREAD::IsDone)
138 printfd(__FILE__, "MAIN_THREAD::CleanupThreads() Active threads: %d\n", connections.size());