-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathex12_4s.c
More file actions
70 lines (60 loc) · 2.05 KB
/
Copy pathex12_4s.c
File metadata and controls
70 lines (60 loc) · 2.05 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
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define PORTNUM 9000
int main(void) {
char buf[256];
struct sockaddr_in sin, cli;
int sd, ns, clientlen = sizeof(cli);
// socket 함수로 소켓을 생성한다.
if((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
printf("** Create Socket\n");
memset((char *)&sin, '\0', sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(PORTNUM);
sin.sin_addr.s_addr = inet_addr("127.0.0.1");
// 특정 IP 주소와 연결한다.
if(bind(sd, (struct sockaddr *)&sin, sizeof(sin))) {
perror("bind");
exit(1);
}
printf("** Bind Socket\n");
// listen 함수로 클라이언트의 접속을 5개까지 처리하도록 설정한다.
if(listen(sd, 5)) {
perror("listen");
exit(1);
}
printf("** Listen Socket\n");
// accept 함수를 사용해 클라이언트와 접속 요청을 받는다.
while(1) {
if((ns = accept(sd, (struct sockaddr *)&cli, &clientlen)) == -1) {
perror("accept");
exit(1);
}
printf("** Accept Client\n");
// fork 함수로 자식 프로세스를 생성하고,
// 해당 자식 프로세스가 클라이언트의 응답을 처리하게 한다.
switch(fork()) {
case 0:
printf("** Fork Client\n");
close(sd);
// 클라이언트와 통신할 수 있는 소켓을 버퍼에 저장한다.
sprintf(buf, "%d", ns);
// execlp 함수를 사용해 bit 프로세스를 호출할 때
// 위에서 저장한 소켓 정보를 인자로 함께 전송한다.
// bit 프로세스가 클라이언트와 연결되어 서비스를 제공할 것이다.
execlp("./bit", "bit", buf, (char *)0);
close(ns);
}
close(ns);
}
return 0;
}