-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp-server-fork.c
More file actions
83 lines (65 loc) · 2.25 KB
/
Copy pathhttp-server-fork.c
File metadata and controls
83 lines (65 loc) · 2.25 KB
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
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#define BUFFSIZE 2048
#define LISTENQ 5
int main(int argc, char *argv[]){
int servSock, cliSock;
unsigned int len;
char inbuf[BUFFSIZE], obuf[BUFFSIZE], buff[BUFFSIZE];
struct sockaddr_in servSockAddr, cliSockAddr;
servSock = socket(AF_INET, SOCK_STREAM, 0);
if(servSock < 0){
perror("socket() failed");
exit(EXIT_FAILURE);
}
servSockAddr.sin_family = AF_INET;
servSockAddr.sin_port = htons(10024+12700); //ポート番号を指定
servSockAddr.sin_addr.s_addr = INADDR_ANY;
if(bind(servSock, (struct sockaddr *)&servSockAddr, sizeof(servSockAddr)) < 0){
perror("bind() failed");
exit(EXIT_FAILURE);
}
if(listen(servSock, LISTENQ) < 0){
perror("listen() failed");
exit(EXIT_FAILURE);
}
while(1){
len = sizeof(cliSockAddr);
cliSock = accept(servSock, (struct sockaddr *) &cliSockAddr, &len);
if(cliSock < 0){
perror("accept() failed");
exit(EXIT_FAILURE);
}
pid_t pid;
if((pid = fork()) == 0){ // 子プロセスなら...
close(servSock); // クライアントからの新たなリクエストを受け付けない
memset(inbuf, 0, sizeof(inbuf));
recv(cliSock, inbuf, sizeof(inbuf), 0);
printf("%s", inbuf);
memset(obuf, 0, sizeof(obuf));
snprintf(obuf, sizeof(obuf),
"HTTP/1.0 200 OK\r\n"
"Content-Type: text/html\r\n"
"\r\n"
"<h1>Hello</h1>\r\n"
);
send(cliSock, obuf, (int)strlen(obuf), 0);
printf("connected from %s, port=%d.\n",
(char *)inet_ntop(AF_INET, &cliSockAddr.sin_addr,
buff, sizeof(buff)),
ntohs(cliSockAddr.sin_port)
);
close(cliSock);
exit(EXIT_FAILURE);
} else { // 親プロセスなら...
close(cliSock); // クライアントとの通信を子プロセスに任せる
}
}
}