-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver_fork.c
More file actions
78 lines (63 loc) · 1.34 KB
/
server_fork.c
File metadata and controls
78 lines (63 loc) · 1.34 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
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define SERVER_ADDR "127.0.0.1"
#define SERVER_PORT 3333
#define BACKLOG 5
void handle_read(int confd);
int main()
{
int fd, confd, sockfd;
struct sockaddr_in addr;
struct sockaddr_in cli_addr;
socklen_t cli_addr_len;
pid_t pid;
memset(&addr, 0, sizeof(addr));
memset(&cli_addr, 0, sizeof(cli_addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(SERVER_ADDR);
addr.sin_port = htons(SERVER_PORT);
if( (fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
printf("error to create the socket\n");
exit(-1);
}
if(bind(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
printf("error to bind the socket\n");
exit(-2);
}
if(listen(fd, BACKLOG) == -1) {
printf("error to listen the socket\n");
exit(-3);
}
while(1) {
confd = accept(fd, NULL, NULL);
//child
if( (pid = fork()) == 0) {
close(fd);
handle_read(confd);
close(confd);
exit(0);
}
close(confd);
}
}
void handle_read(int confd)
{
char buf[16];
int num = 0;
while( (num = read(confd, buf, 15)) > 0) {
buf[num] = '\0';
printf("%s\n", buf);
}
if(num == 0) {
printf("client close the connection\n");
}
else if(num < 0) {
printf("connection error\n");
}
}