Last active
March 14, 2018 03:56
-
-
Save Dzejrou/64518b7cec5207126a971fed52e3b5ca to your computer and use it in GitHub Desktop.
atexit implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Standard requires atleast 32, but except | |
* for this upper bound the limit is implementation | |
* defined. | |
*/ | |
#define ATEXIT_HANDLER_LIMIT 32 | |
typedef void (*atexit_handler_t)(void); | |
static atexit_handler_t static_handlers[ATEXIT_HANDLER_LIMIT]; | |
static size_t static_handler_count = 0; | |
static atexit_handler_t *dynamic_handlers = NULL; | |
static size_t dynamic_handler_size = ATEXIT_HANDLER_LIMIT; | |
static size_t dynamic_handler_count = 0; | |
int atexit(atexit_handler_t handler) | |
{ | |
if (!handler) | |
return -1; | |
if (static_handler_count < ATEXIT_HANDLER_LIMIT) | |
static_handlers[static_handler_count++] = handler; | |
else { | |
if (dynamic_handler_count == 0 || | |
dynamic_handler_count >= dynamic_handler_size) { | |
dynamic_handler_size *= 2; | |
atexit_handler_t *new_handlers = realloc( | |
dynamic_handlers, | |
dynamic_handler_size * sizeof(atexit_handler_t) | |
); | |
if (!new_handlers) | |
return -1; | |
else | |
dynamic_handlers = new_handlers; | |
} | |
dynamic_handlers[dynamic_handler_count++] = handler; | |
} | |
return 0; | |
} | |
/** | |
* To silence GCC warning about a missing prototype. | |
*/ | |
void call_atexit_handlers(void); | |
void call_atexit_handlers(void) | |
{ | |
for (size_t i = dynamic_handler_count; i > 0; --i) | |
dynamic_handlers[i - 1](); | |
free(dynamic_handlers); | |
dynamic_handler_count = 0; | |
dynamic_handler_size = ATEXIT_HANDLER_LIMIT; | |
for (size_t i = static_handler_count; i > 0; --i) | |
static_handlers[i - 1](); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment