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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
| #define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <assert.h>
#include <sys/wait.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sched.h>
#include <pthread.h>
#include <netinet/tcp.h>
#define IP "192.168.3.6"
#define PORT 80
#define WORKER 8
#define MAXLINE 4096
int worker(int i)
{
struct sockaddr_in address;
bzero(&address, sizeof(address));
address.sin_family = AF_INET;
inet_pton( AF_INET, IP, &address.sin_addr);
address.sin_port = htons(PORT);
pid_t pid = getpid();
unsigned cc = 0;
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(i, &mask);
printf("pid=%d %d\n", pid, i);
if (sched_getaffinity(pid, sizeof(mask), &mask) < 0) {
printf("sched_getaffinity err\n");
}
int listenfd = socket(PF_INET, SOCK_STREAM, 0);
assert(listenfd >= 0);
int val =1;
/*set SO_REUSEPORT*/
if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEPORT, &val, sizeof(val)) < 0) {
perror("setsockopt()");
}
val = 1000 + i;
if (setsockopt(listenfd, SOL_TCP, TCP_MAXSEG, &val, sizeof(val))<0) {
perror("setsockopt()");
}
int ret = bind(listenfd, (struct sockaddr*)&address, sizeof(address));
assert(ret != -1);
ret = listen(listenfd, 5);
assert(ret != -1);
while (1) {
cc ++;
if (cc % 100 == 0)
printf("thread=%d cc=%d\n", i, cc);
// printf("I am worker %d, begin to accept connection.\n", i);
struct sockaddr_in client_addr;
socklen_t client_addrlen = sizeof( client_addr );
int connfd = accept(listenfd, (struct sockaddr*)&client_addr, &client_addrlen);
if (connfd != -1) {
// printf("worker %d accept a connection success. ip:%s, prot:%d\n", i, inet_ntoa(client_addr.sin_addr), client_addr.sin_port);
} else {
// printf("worker %d accept a connection failed,error:%s", i, strerror(errno));
}
char buffer[MAXLINE];
// int nbytes = read(connfd, buffer, MAXLINE);
// printf("read from client is:%s\n", buffer);
// write(connfd, buffer, nbytes);
close(connfd);
}
return 0;
}
int main()
{
int i = 0;
for (i = 0; i < WORKER; i++) {
printf("Create worker %d\n", i);
pid_t pid = fork();
/*child process */
if (pid == 0) {
worker(i);
}
if (pid < 0) {
printf("fork error");
}
}
/*wait child process*/
while (wait(NULL) != 0)
;
if (errno == ECHILD) {
fprintf(stderr, "wait error:%s\n", strerror(errno));
}
return 0;
}
|