-
Notifications
You must be signed in to change notification settings - Fork 0
/
TCPMainServer-Thread.c
54 lines (39 loc) · 1.68 KB
/
TCPMainServer-Thread.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
#include "TCPServer.h" /* TCP server includes */
#include <pthread.h> /* for POSIX threads */
#define SERV_PORT 9999 /* Server will run on this port */
void *ThreadMain(void *arg); /* Main program of a thread */
/* Structure of arguments to pass to client thread */
struct ThreadArgs{
int clntSock;
};
int main(int argc, char *argv[]){
int servSock; /* Socket descriptor for server */
int clntSock; /* Socket descriptor for client */
unsigned short servPort; /* Server port */
pthread_t threadID; /* Thread ID from pthread_create() */
struct ThreadArgs *threadArgs; /* Pointer to argument structure for thread */
/* Create server socket */
servPort = SERV_PORT;
servSock = CreateTCPServerSocket(servPort);
for(;;){ /* Run forever */
clntSock = AcceptTCPConnection(servSock);
/* Create separate memory for client argument */
if((threadArgs = (struct ThreadArgs *) malloc(sizeof(struct ThreadArgs))) == NULL)
DieWithError("malloc() failed");
threadArgs->clntSock = clntSock;
/* Create client thread */
if(pthread_create(&threadID, NULL, ThreadMain, (void *) threadArgs) != 0)
DieWithError("pthread_create() failed");
}
/* NOT REACHED */
}
void *ThreadMain(void *threadArgs){
int clntSock; /* Socket descriptot for client connection */
/* Guarantees that thread resources are deallocated upon return */
pthread_detach(pthread_self());
/* Extract socket file descriptor from argument */
clntSock = ((struct ThreadArgs *) threadArgs) -> clntSock;
free(threadArgs); /* Deallocate memory for argument */
HandleTCPClient(clntSock);
return (NULL);
}