1. #include <pthread.h>
    2. #include <signal.h>
    3. #include "net.h"
    4. void cli_data_handle (void *arg);
    5. void sig_child_handle(int signo)
    6. {
    7. if(SIGCHLD == signo) {
    8. waitpid(-1, NULL, WNOHANG);
    9. }
    10. }
    11. int main (void)
    12. {
    13. int fd = -1;
    14. signal(SIGCHLD, sig_child_handle);
    15. /* 1. 创建socket fd */
    16. if ((fd = socket (AF_LOCAL, SOCK_STREAM, 0)) < 0) { //基于本地的TCP通信
    17. perror ("socket");
    18. exit (1);
    19. }
    20. /* 允许绑定地址快速重用 */
    21. int b_reuse = 1;
    22. setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, &b_reuse, sizeof (int));
    23. /* 2.1 填充sockaddr_un结构体变量 */
    24. struct sockaddr_un sun;
    25. bzero(&sun, sizeof(sun));
    26. sun.sun_family = AF_LOCAL;
    27. /* 如果UNIX_DOMAIN_FILE所指向的文件存在,则删除 */
    28. if(!access(UNIX_DOMAIN_FILE, F_OK)) {
    29. unlink(UNIX_DOMAIN_FILE);
    30. }
    31. strncpy(sun.sun_path, UNIX_DOMAIN_FILE, strlen( UNIX_DOMAIN_FILE));
    32. /*2.2 绑定 */
    33. if (bind (fd, (struct sockaddr *) &sun, sizeof (sun)) < 0) {
    34. perror ("bind");
    35. exit (1);
    36. }
    37. /*3. 调用listen()把主动套接字变成被动套接字 */
    38. if (listen (fd, BACKLOG) < 0) {
    39. perror ("listen");
    40. exit (1);
    41. }
    42. printf ("Unix domain server starting....OK!\n");
    43. int newfd = -1;
    44. /*4. 阻塞等待客户端连接请求 */
    45. while(1) {
    46. pid_t pid = -1;
    47. if ((newfd = accept (fd, NULL,NULL)) < 0) {
    48. perror ("accept");
    49. break;
    50. }
    51. /*创建一个子进程用于处理已建立连接的客户的交互数据*/
    52. if((pid = fork()) < 0) {
    53. perror("fork");
    54. break;
    55. }
    56. if(0 == pid) { //子进程中
    57. close(fd);
    58. printf ("Clinet is connected!\n");
    59. cli_data_handle(&newfd);
    60. return 0;
    61. } else { //实际上此处 pid >0, 父进程中
    62. close(newfd);
    63. }
    64. }
    65. close (fd);
    66. return 0;
    67. }
    68. void cli_data_handle (void *arg)
    69. {
    70. int newfd = *(int *) arg;
    71. printf ("Child handling process: newfd =%d\n", newfd);
    72. //..和newfd进行数据读写
    73. int ret = -1;
    74. char buf[BUFSIZ];
    75. char resp_buf[BUFSIZ+10];
    76. while (1) {
    77. bzero (buf, BUFSIZ);
    78. do {
    79. ret = read (newfd, buf, BUFSIZ - 1);
    80. } while (ret < 0 && EINTR == errno);
    81. if (ret < 0) {
    82. perror ("read");
    83. exit (1);
    84. }
    85. if (!ret) { //对方已经关闭
    86. break;
    87. }
    88. printf ("Receive data: %s\n", buf);
    89. if (!strncasecmp (buf, QUIT_STR, strlen (QUIT_STR))) { //用户输入了quit字符
    90. printf ("Client(fd=%d) is exiting!\n", newfd);
    91. break;
    92. }
    93. bzero(resp_buf, BUFSIZ+10);
    94. strncpy(resp_buf, SERV_RESP_STR, strlen(SERV_RESP_STR));
    95. strcat(resp_buf, buf);
    96. do {
    97. ret = write(newfd, resp_buf, strlen(resp_buf));
    98. }while(ret < 0 && EINTR == errno);
    99. }
    100. close (newfd);
    101. }