diff --git a/mx_util.c b/mx_util.c index 14741ba..0829ae9 100644 --- a/mx_util.c +++ b/mx_util.c @@ -607,3 +607,20 @@ int mx_sleep_nofail(unsigned int seconds) mx_sleep(seconds); return 1; } + +void *mx_calloc_forever_sec(size_t nmemb, size_t size, unsigned int time) +{ + void *ptr; + + while (1) { + ptr = calloc(nmemb, size); + if (ptr) + break; + + mx_log_debug("calloc() failed: %m - retrying (forever) in %d second(s).", time); + if (time) + mx_sleep(time); + } + + return ptr; +} diff --git a/mx_util.h b/mx_util.h index 63af526..9fac460 100644 --- a/mx_util.h +++ b/mx_util.h @@ -96,4 +96,12 @@ int mx_open_newfile(char *fname); int mx_sleep(unsigned int seconds); int mx_sleep_nofail(unsigned int seconds); +#ifndef MX_CALLOC_FAIL_WAIT_DEFAULT +# define MX_CALLOC_FAIL_WAIT_DEFAULT 1 +#endif + +#define mx_calloc_forever(n, s) mx_calloc_forever_sec((n), (s), MX_CALLOC_FAIL_WAIT_DEFAULT) + +void *mx_calloc_forever_sec(size_t nmemb, size_t size, unsigned int time); + #endif