forked from JamesKoenig/Gs503ToSql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserverFns.c
90 lines (74 loc) · 1.67 KB
/
serverFns.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
#include <stdlib.h>
#include "serverFns.h"
#include "server.h"
#include "thread.h"
#include "socket.h"
#include "servMain.h"
unsigned servOn(Server * srv)
{
return srv->controls.vals.power = 1;
}
unsigned servOff(Server * srv)
{
return srv->controls.vals.power = 0;
}
unsigned servStatus(Server * srv)
{
return srv->controls.vals.power;
}
void * serverThread(void * args)
{
Server * me = (Server *) args;
while(servStatus(me))
{
servLoop(me);
}
return NULL;
}
Server * makeServer(unsigned short port)
{
//start with the empty server
Server * srv = NULL;
srv = malloc(sizeof(srv));
if(!srv) return NULL;
servOff(srv);
srv->socket = listenOnPort(port);
srv->port = port;
srv->errOut = stderr;
srv->serverThread = (pthread_t) 0;
if(!(srv->socket)) return NULL;
return srv;
}
int startServer(Server * srv)
{
//tell the server it's on, this has to be done first because
//the server thread checks for it
servOn(srv);
srv->serverThread = makeThread(serverThread, srv);
//if the server thread has not been made
if(!(srv->serverThread))
{
//turn off the server power flag
servOff(srv);
return 0;
}
//server is now running, return success
else return 1;
}
int stopServer(Server * srv)
{
//turn off the server
servOff(srv);
//join with the server thread (wait for it to die)
//discard its output
pthread_join(srv->serverThread, NULL);
return 1;
}
void delServer(Server * srv)
{
//make sure to stop the server thread
stopServer(srv);
close(srv->socket);
free(srv);
return;
}