From 6c0d5642ba4ad4edfc5b5b107b7468cb8c62f773 Mon Sep 17 00:00:00 2001 From: Jeffrey Hsu Date: Mon, 9 Sep 2024 08:28:04 +0800 Subject: [PATCH] add exit condition and fix potential memory leak --- main.c | 40 ++++++++++++++++++++++++---------------- 1 file changed, 24 insertions(+), 16 deletions(-) diff --git a/main.c b/main.c index e131494..77f0c06 100644 --- a/main.c +++ b/main.c @@ -18,7 +18,7 @@ } #ifdef Debug -#define DPRINT(s, __VA_ARGS__) \ +#define DPRINT(s, __VA_ARGS__) \ { \ printf(s, ...); \ } @@ -37,11 +37,13 @@ long long current_timestamp(); size_t cb(char *, size_t, size_t, void *); char *get_enc(); void parise(void *); +void exit_handler(); const char ENC_URL[] = "https://lbapi-rk.chaoxing.com/lb/parise/enc/get?subRoomId=%s×tamp=%llu&ss=%s"; const char URL[] = "https://zhibo.chaoxing.com/apis/live/setLivePariseCountByEnc?subroomId=%s&enc=%s×tamp=%llu"; const char SUBROOMID[] = "381236458034402305"; const char SS[] = "381237373432790016"; +static int flag = 1; int main(int argc, char *argv[]) { @@ -57,27 +59,25 @@ int main(int argc, char *argv[]) curl_global_init(CURL_GLOBAL_ALL); - printf("线程\t状态\t点赞量\n"); + printf("线程\t状态\t点赞量\t(按下回车键退出)\n"); - pthread_t **thread_pool = malloc(sizeof(pthread_t *) * thread); + pthread_t *thread_pool = malloc(sizeof(pthread_t) * thread); for (int i = 0; i < thread; i++) { - thread_pool[i] = malloc(sizeof(pthread_t)); - pthread_create(thread_pool[i], NULL, (void *)&parise, (void *)i); + if (i == thread - 1) + pthread_create(&thread_pool[i], NULL, (void *)&exit_handler, NULL); + else + pthread_create(&thread_pool[i], NULL, (void *)&parise, (void *)i); } for (int i = 0; i < thread; i++) - { - pthread_join(*thread_pool[i], NULL); - } + pthread_join(thread_pool[i], NULL); + + free(thread_pool); curl_global_cleanup(); - for (int i = 0; i < 8; i++) - { - free(thread_pool[i]); - } return 0; } @@ -130,7 +130,7 @@ size_t cb(char *data, size_t size, size_t nmemb, void *clientp) return 0; /* out of memory! */ mem->response = ptr; - memcpy(&(mem->response[mem->size]), data, realsize); + memcpy(&mem->response[mem->size], data, realsize); mem->size += realsize; mem->response[mem->size] = 0; @@ -164,10 +164,11 @@ char *get_enc() // {'data': 293687, 'msg': '操作成功', 'result': 1} void parise(void *arg) { - while (true) + const int idx = (int)arg; + + while (flag) { char url[200]; - const int idx = (int)arg; struct memory json_c = {0}; const char *enc = get_enc(); const cJSON *result = NULL; @@ -196,4 +197,11 @@ void parise(void *arg) cJSON_Delete(json); } -} \ No newline at end of file + printf("Signal: exit, T%d exiting\n", idx); +} + +void exit_handler() +{ + getchar(); + flag = 0; +}