1. void *run(void *ff) {
    2. int fd = *(int *) (ff);
    3. char *hello = "hello chenshun!";
    4. char cc[11];
    5. ssize_t rr = read(fd, cc, 10);
    6. if (rr == -1) {
    7. close(fd);
    8. }
    9. printf("i receive your message:%s\n", cc);
    10. write(fd, hello, strlen(hello));
    11. write(fd, "good bye!", strlen("good bye!"));
    12. close(fd);
    13. return 0;
    14. }
    15. int main() {
    16. int serv_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //AF_INT:ipv4, SOCK_STREAM:tcp协议
    17. //将套接字和IP、端口绑定
    18. struct sockaddr_in *serv_addr = malloc(sizeof(struct sockaddr_in));
    19. serv_addr->sin_family = AF_INET; //使用IPv4地址
    20. serv_addr->sin_addr.s_addr = inet_addr("127.0.0.1"); //具体的IP地址
    21. serv_addr->sin_port = htons(11234); //端口
    22. int on = 1;
    23. if (setsockopt(serv_sock, SOL_SOCKET, SO_REUSEPORT, &on, sizeof(on)) == -1) {
    24. printf("处理失败SO_REUSEPORT失败");
    25. exit(1);
    26. }
    27. bind(serv_sock, (struct sockaddr *) serv_addr, sizeof(struct sockaddr));
    28. listen(serv_sock, 20);
    29. for (;;) {
    30. int fd = accept(serv_sock, NULL, NULL);
    31. pthread_attr_t attr;
    32. pthread_t thread;
    33. size_t stacksize;
    34. pthread_attr_init(&attr);
    35. pthread_attr_getstacksize(&attr, &stacksize);
    36. if (!stacksize) stacksize = 1; /* The world is full of Solaris Fixes */
    37. while (stacksize < REDIS_THREAD_STACK_SIZE) stacksize *= 2;
    38. pthread_attr_setstacksize(&attr, stacksize);
    39. int res = pthread_create(&thread, &attr, run, &fd);
    40. printf("创建线程执行:%d\n", res);
    41. if (res != 0) {
    42. exit(-1);
    43. }
    44. }
    45. return 0;
    46. }