-
Notifications
You must be signed in to change notification settings - Fork 2
/
servers.c
102 lines (87 loc) · 2.19 KB
/
servers.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include <errno.h>
#include <assert.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "servers.h"
#include "clients.h"
#include "params.h"
#include "error.h"
#include "set.h"
#include "net.h"
#define MAX(X,Y) (X>Y)?X:Y
#define MIN(X,Y) (X<Y)?X:Y
struct TServers g_servers = { NULL, 0 };
void server_add(int sock)
{
int newcount = g_servers.m_count + 1;
struct TServer* servers = (struct TServer*)malloc( sizeof(struct TServer) * newcount );
memcpy( servers, g_servers.m_server, sizeof(struct TServer) * g_servers.m_count );
servers[g_servers.m_count].m_sock = sock;
set_add( 2 + g_servers.m_count , sock, POLLIN );
free( g_servers.m_server );
g_servers.m_server = servers;
g_servers.m_count = newcount;
}
void server_del(int sock)
{
int newcount = g_servers.m_count + 1;
struct TServer* servers = (struct TServer*)malloc( sizeof(struct TServer) * newcount );
int index;
for (index = 0; g_servers.m_server[index].m_sock != sock && index < g_servers.m_count; ++index)
servers[index] = g_servers.m_server[index];
set_del( 2 + index );
for (++index; index < g_servers.m_count; ++index)
servers[index-1] = g_servers.m_server[index];
free( g_servers.m_server );
g_servers.m_server = servers;
g_servers.m_count = newcount;
}
void server_closeall()
{
int index;
for (index = 0; index < g_servers.m_count; ++index)
{
close( g_servers.m_server[index].m_sock );
set_del( 2 );
}
free( g_servers.m_server );
g_servers.m_server = NULL;
g_servers.m_count = 0;
}
int is_server(int index)
{
return (index < (2 + g_servers.m_count)) && (index >= 2);
}
int servers_loop(int nready)
{
int index;
for (index = 2; nready > 0 && is_server( index ); ++index)
{
/* check for events */
if ( g_set[index].revents )
{
--nready;
}
else
{
continue;
}
/**/
assert( g_set[index].revents & POLLIN );
/* accept new connection */
int client_sock = accept( g_set[index].fd, NULL, NULL );
if ( client_sock == -1 )
{
error_accept( errno );
exit( EXIT_FAILURE );
}
client_add( client_sock );
if ( p_once )
{
server_closeall();
return 0;
}
}
return nready;
}