From 24da58b43f922ab7aa378d864a83b10746076ac8 Mon Sep 17 00:00:00 2001 From: Olivier Matz Date: Thu, 7 Mar 2019 19:14:32 +0100 Subject: [PATCH] support exit callback registration --- include/ecoli_init.h | 18 +++++++++++++++++- src/ecoli_init.c | 12 +++++++++++- test/test.c | 2 ++ 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/include/ecoli_init.h b/include/ecoli_init.h index 4e8bc1e..80a0c01 100644 --- a/include/ecoli_init.h +++ b/include/ecoli_init.h @@ -14,6 +14,11 @@ #include #include +/** + * Register initialization and exit callbacks. These callbacks are + * ordered by priority: for initialization, the lowest priority is called + * first. For exit, the callbacks are invoked in reverse order. + */ #define EC_INIT_REGISTER(t) \ static void ec_init_init_##t(void); \ static void __attribute__((constructor, used)) \ @@ -27,6 +32,11 @@ */ typedef int (ec_init_t)(void); +/** + * Type of exit function. + */ +typedef void (ec_exit_t)(void); + TAILQ_HEAD(ec_init_list, ec_init); /** @@ -35,6 +45,7 @@ TAILQ_HEAD(ec_init_list, ec_init); struct ec_init { TAILQ_ENTRY(ec_init) next; /**< Next in list. */ ec_init_t *init; /**< Init function. */ + ec_exit_t *exit; /**< Exit function. */ unsigned int priority; /**< Priority (0=first, 99=last) */ }; @@ -47,7 +58,7 @@ struct ec_init { void ec_init_register(struct ec_init *test); /** - * Initialize ecoli library + * Initialize ecoli library. * * Must be called before any other function from libecoli, except * ec_malloc_register(). @@ -57,4 +68,9 @@ void ec_init_register(struct ec_init *test); */ int ec_init(void); +/** + * Uninitialize ecoli library. + */ +void ec_exit(void); + #endif diff --git a/src/ecoli_init.c b/src/ecoli_init.c index fd5c0c3..a1c86e6 100644 --- a/src/ecoli_init.c +++ b/src/ecoli_init.c @@ -38,9 +38,19 @@ int ec_init(void) struct ec_init *init; TAILQ_FOREACH(init, &init_list, next) { - if (init->init() < 0) + if (init->init != NULL && init->init() < 0) return -1; } return 0; } + +void ec_exit(void) +{ + struct ec_init *init; + + TAILQ_FOREACH_REVERSE(init, &init_list, ec_init_list, next) { + if (init->exit != NULL) + init->exit(); + } +} diff --git a/test/test.c b/test/test.c index c874af9..d60adfc 100644 --- a/test/test.c +++ b/test/test.c @@ -390,6 +390,8 @@ int main(int argc, char **argv) ret |= ec_test_one(argv[i]); } + ec_exit(); + leaks = debug_alloc_dump_leaks(); if (alloc_fail_proba == 0 && ret != 0) { -- 2.20.1