void *run(void *ff) {
int fd = *(int *) (ff);
char *hello = "hello chenshun!";
char cc[11];
ssize_t rr = read(fd, cc, 10);
if (rr == -1) {
close(fd);
}
printf("i receive your message:%s\n", cc);
write(fd, hello, strlen(hello));
write(fd, "good bye!", strlen("good bye!"));
close(fd);
return 0;
}
int main() {
int serv_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //AF_INT:ipv4, SOCK_STREAM:tcp协议
//将套接字和IP、端口绑定
struct sockaddr_in *serv_addr = malloc(sizeof(struct sockaddr_in));
serv_addr->sin_family = AF_INET; //使用IPv4地址
serv_addr->sin_addr.s_addr = inet_addr("127.0.0.1"); //具体的IP地址
serv_addr->sin_port = htons(11234); //端口
int on = 1;
if (setsockopt(serv_sock, SOL_SOCKET, SO_REUSEPORT, &on, sizeof(on)) == -1) {
printf("处理失败SO_REUSEPORT失败");
exit(1);
}
bind(serv_sock, (struct sockaddr *) serv_addr, sizeof(struct sockaddr));
listen(serv_sock, 20);
for (;;) {
int fd = accept(serv_sock, NULL, NULL);
pthread_attr_t attr;
pthread_t thread;
size_t stacksize;
pthread_attr_init(&attr);
pthread_attr_getstacksize(&attr, &stacksize);
if (!stacksize) stacksize = 1; /* The world is full of Solaris Fixes */
while (stacksize < REDIS_THREAD_STACK_SIZE) stacksize *= 2;
pthread_attr_setstacksize(&attr, stacksize);
int res = pthread_create(&thread, &attr, run, &fd);
printf("创建线程执行:%d\n", res);
if (res != 0) {
exit(-1);
}
}
return 0;
}