From c37dd02f572f289037cbfbae3024b6b7fd73b848 Mon Sep 17 00:00:00 2001 From: Xiao Pan Date: Fri, 31 May 2024 16:25:38 -0700 Subject: fix: dynotify: check curl retuen so when failed it will not crash Before when no internet, curl error "curl_easy_perform() failed: Couldn't resolve host name" will cause `json_tokener_parse(chunk.response)` to crash the program with error "Segmentation fault (core dumped)". I guess maybe because chunk.response is NULL because curl error not assign value to it. Now I check return error code of curl to break the loop and wait a minute to see if error gone and proceed forward. Maybe also check chunk.response and json function error code somehow. --- dynotify.c | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/dynotify.c b/dynotify.c index 3839e35..ec7cea8 100644 --- a/dynotify.c +++ b/dynotify.c @@ -1,5 +1,5 @@ // curl: -// man curl_easy_init CURLOPT_URL curl_easy_setopt CURLOPT_WRITEFUNCTION +// man curl_easy_init CURLOPT_URL curl_easy_setopt CURLOPT_WRITEFUNCTION libcurl-errors curl_easy_strerror // https://curl.se/libcurl/ // https://curl.se/libcurl/c/ // https://curl.se/libcurl/c/libcurl-tutorial.html @@ -79,8 +79,8 @@ static size_t cb(char *data, size_t size, size_t nmemb, void *clientp) int main (void) { - // https://curl.se/libcurl/c/libcurl-errors.html - //CURLcode res; + // man libcurl-errors + CURLcode res; // `man curl_easy_init`: "It is encouraged to reuse easy handles for repeated transfers.", so I choose to reuse it CURL *curl = curl_easy_init(); NotifyNotification *n; @@ -100,8 +100,14 @@ int main (void) curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cb); curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk); - //res = curl_easy_perform(curl); - curl_easy_perform(curl); + res = curl_easy_perform(curl); + // man curl_easy_strerror + if(res != CURLE_OK) + { + fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); + free(chunk.response); + break; + } //printf("%s\n",chunk.response); json_object *root; -- cgit v1.2.3-70-g09d2