APUE course source code
guowenxue
2 days ago 01c119252bae1e252aa9e6bdba99f1b2ee756624
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
/*********************************************************************************
 *      Copyright:  (C) 2025 LingYun IoT System Studio
 *                  All rights reserved.
 *
 *       Filename:  socketd_epoll.c
 *    Description:  This file is TCP socket server(epoll) example program.
 *
 *        Version:  1.0.0(10/20/2025)
 *         Author:  Guo Wenxue <guowenxue@gmail.com>
 *      ChangeLog:  1, Release initial version on "10/20/2025 09:48:51 PM"
 *
 ********************************************************************************/
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <getopt.h>
#include <ctype.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <pthread.h>
#include <sys/epoll.h>
 
#define BACKLOG             13
#define MAX_EVENTS          4096
#define ARRAY_SIZE(x)       (sizeof(x)/sizeof(x[0]))
 
int         g_stop = 0; /* program stop or not */
 
void sig_handler(int signum);
int socket_init(int port);
 
void print_usage(char *progname)
{
    printf("%s usage: \n", progname);
    printf("  -p(--port): sepcify listen port.\n");
    printf("  -h(--Help): print this help information.\n");
 
    return ;
}
 
int main(int argc, char **argv)
{
    int                     i, j;
    int                     rv = -1;
    int                     listen_fd,  client_fd = -1;
    int                     port = 10086;
    int                     debug = 0;
    struct sockaddr_in      cli_addr;
    socklen_t               addr_len = sizeof(cli_addr);
    char                    buf[1024];
 
    int                     fd;
    int                     epfd;
    int                     nfds = 0;
    struct epoll_event      ev, events[MAX_EVENTS];
 
    int                     ch;
    struct option           opts[] = {
        {"debug", no_argument, NULL, 'd'},
        {"port", required_argument, NULL, 'p'},
        {"help", no_argument, NULL, 'h'},
        {NULL, 0, NULL, 0}
    };
 
    /* 解析命令行参数 */
    while( (ch=getopt_long(argc, argv, "dp:h", opts, NULL)) != -1 )
    {
        switch(ch)
        {
            case 'd':
                debug = 1;
                break;
 
            case 'p':
                port=atoi(optarg);
                break;
 
            case 'h':
                print_usage(argv[0]);
                return 0;
        }
    }
 
    /* 如果不是debug调试运行,就放到后台去运行 */
    if( !debug )
        daemon(0, 0);
 
    /* 安装信号 */
    signal(SIGTERM, sig_handler);  /* capture kill/killall signal */
    signal(SIGINT,  sig_handler);  /* capture Ctrl+C signal */
    signal(SIGSEGV, sig_handler);  /* capture segmentation fault signal */
    signal(SIGPIPE, sig_handler);  /* capture socket error signal */
 
    /* 创建监听套接字 */
    if( (listen_fd = socket_init(port)) < 0 )
        return 2;
 
    /* 创建 epoll 实例 */
    epfd = epoll_create1(0);
    if (epfd < 0)
    {
        printf("epoll_create1 failure: %s\n", strerror(errno));
        return 1;
    }
 
    /* 注册监听 socket 到 epoll 实例 */
    ev.events = EPOLLIN;
    ev.data.fd = listen_fd;
    if (epoll_ctl(epfd, EPOLL_CTL_ADD, listen_fd, &ev) < 0)
    {
        printf("epoll_ctrl add listen_fd failure: %s\n", strerror(errno));
        return -1;
    }
 
    while( !g_stop )
    {
        /* epoll 一直阻塞等待, 永不超时 */
        nfds = epoll_wait(epfd, events, MAX_EVENTS, -1);
        if( nfds <= 0 )
        {
            /* poll()超时或有异常发生(如有信号到来),继续下次循环 */
            printf("poll failure: %s\n", strerror(errno));
            continue;
        }
 
        /* 程序走到这里说明 rv>0, 有文件描述符发生事件了 */
 
        /*  逐个处理就绪事件 */
        for(i=0; i<nfds; i++)
        {
            fd = events[i].data.fd;
 
            /* 检查是不是 listen_fd 发生了事件,如果有说明有新的客户端连接请求到来 */
            if ( fd == listen_fd )
            {
                /* 接收新的客户端连接请求 */
                client_fd = accept(listen_fd, (struct sockaddr*)&cli_addr, &addr_len);
                if(client_fd < 0)
                {
                    printf("accept new socket failure: %s\n", strerror(errno));
                    continue;
                }
                printf("Accept new client[%s:%d] with fd [%d]\n",
                        inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port), client_fd);
 
                /* 新的客户端加入 epoll 监听 */
 
                ev.events = EPOLLIN | EPOLLRDHUP; /* 可读 + 对端关闭检测 */
                ev.data.fd = client_fd;
                if (epoll_ctl(epfd, EPOLL_CTL_ADD, client_fd, &ev) < 0)
                {
                    perror("epoll_ctl add client");
                    close(client_fd);
                }
 
            }
            /* 接下来都是客户端 socket 有数据到来或断开时间 */
            else if (events[i].events & EPOLLIN)
            {
                memset(buf, 0, sizeof(buf));
                if( (rv=read(fd, buf, sizeof(buf))) <= 0)
                {
                    printf("socket[%d] get disconncet\n", fd);
                    epoll_ctl(epfd, EPOLL_CTL_DEL, fd, NULL);
                    close(fd);
                    continue;
                }
                printf("socket[%d] client read %d bytes data: %s\n", fd, rv, buf);
 
                /* 将收到的字符串统一转成大写 */
                for(j=0; j<rv; j++)
                {
                    buf[i]=toupper(buf[i]);
                }
 
                /* 将处理后的数据返回给客户端 */
                rv=write(fd, buf, rv);
                if(rv <= 0)
                {
                    printf("socket[%d] write failure: %s\n", fd, strerror(errno));
 
                    /* 客户端关闭时要把这个位置空出来 */
                    epoll_ctl(epfd, EPOLL_CTL_DEL, fd, NULL);
                    close(fd);
                    continue;
                }
            }
 
            /* 处理异常或挂起事件 */
            if ( events[i].events & (EPOLLHUP | EPOLLERR | EPOLLRDHUP) )
            {
                printf("socket[%d] closed or error\n", fd);
                epoll_ctl(epfd, EPOLL_CTL_DEL, fd, NULL);
                close(fd);
                continue;
            }
        }
    }
 
    close(epfd);
    close(listen_fd);
    return 0;
}
 
void sig_handler(int signum)
{
    switch(signum)
    {
        case SIGTERM:
            printf("SIGTERM signal detected(kill/killall)\n");
            break;
 
        case SIGSEGV:
            printf("SIGSEGV signal detected(segmentation fault)\n");
            break;
 
        case SIGPIPE:
            printf("SIGPIPE signal detected(socket error)\n");
            break;
 
        case SIGINT:
            printf("SIGINT signal detected(Ctrl+C)\n");
            break;
 
        default:
            break;
    }
 
    g_stop = 1;
}
 
int socket_init(int port)
{
    int                     listen_fd;
    int                     reuse = 1;
    struct rlimit           limit;
    struct sockaddr_in      serv_addr;
 
    /* set Max. fd limit */
    getrlimit(RLIMIT_NOFILE, &limit);
    limit.rlim_cur = limit.rlim_max;
    setrlimit(RLIMIT_NOFILE, &limit);
 
    /* create TCP socket */
    listen_fd = socket(AF_INET, SOCK_STREAM, 0);
    if(listen_fd < 0 )
    {
        printf("create socket failure: %s\n", strerror(errno));
        return -1;
    }
 
    /* resolve the "Address already in use" error when using bind() */
    setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
 
    /* bind socket server information */
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(port);
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    if( bind(listen_fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0 )
    {
        printf("bind socket failure: %s\n", strerror(errno));
        return -2;
    }
    printf("socket[%d] bind on port[%d] for all IP address ok\n", listen_fd, port);
 
    /* start listen socket */
    listen(listen_fd, BACKLOG);
 
    return listen_fd;
}