-
Notifications
You must be signed in to change notification settings - Fork 0
/
HTTPTCPServer-Fork.c
54 lines (45 loc) · 1.98 KB
/
HTTPTCPServer-Fork.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 "TCPEchoServer.h" /* TCP echo server includes */
#include <sys/wait.h> /* for waitpid() */
int main(int argc, char *argv[])
{
int servSock; /* Socket descriptor for server */
int clntSock; /* Socket descriptor for client */
unsigned short echoServPort; /* Server port */
pid_t processID; /* Process ID from fork() */
unsigned int childProcCount = 0; /* Number of child processes */
char *html_path = argv[2]; //assign html_path argument
if (argc != 3) /* Test for correct number of arguments */
{
fprintf(stderr, "Usage: %s <Server Port>\n", argv[0]);
exit(1);
}
echoServPort = atoi(argv[1]); /* First arg: local port */
servSock = CreateTCPServerSocket(echoServPort);
for (;;) /* Run forever */
{
clntSock = AcceptTCPConnection(servSock);
/* Fork child process and report any errors */
if ((processID = fork()) < 0)
DieWithError("fork() failed");
else if (processID == 0) /* If this is the child process */
{
close(servSock); /* Child closes parent socket */
HandleTCPClient(clntSock, html_path); //send html_path as argument
exit(0); /* Child process terminates */
}
printf("with child process: %d\n", (int) processID);
close(clntSock); /* Parent closes child socket descriptor */
childProcCount++; /* Increment number of outstanding child processes */
while (childProcCount) /* Clean up all zombies */
{
processID = waitpid((pid_t) -1, NULL, WNOHANG); /* Non-blocking wait */
if (processID < 0) /* waitpid() error? */
DieWithError("waitpid() failed");
else if (processID == 0) /* No zombie to wait on */
break;
else
childProcCount--; /* Cleaned up after a child */
}
}
/* NOT REACHED */
}