X-Git-Url: http://git.madism.org/?a=blobdiff_plain;f=common.c;h=d3147ffc82c7bdd36a66bc4d12a70838fb8f7253;hb=cf48fad99532b7590b8bfea416532a7a84910bdf;hp=eba691bd9721d82e74a86ce9c1410d8476bcb1d1;hpb=360aa52da7c498ea412635a5ff4d832adb0488cc;p=apps%2Fpfixtools.git diff --git a/common.c b/common.c index eba691b..d3147ff 100644 --- a/common.c +++ b/common.c @@ -40,9 +40,10 @@ #include "common.h" -sig_atomic_t cleanexit = false; -sig_atomic_t sigint = false; -sig_atomic_t sighup = false; +sig_atomic_t sigint = false; +sig_atomic_t sighup = false; + +static FILE *pidfile = NULL; void common_sighandler(int sig) { @@ -205,22 +206,62 @@ int drop_privileges(const char *user, const char *group) return 0; } -void common_initialize(void) +int pidfile_open(const char *name) +{ + if (name) { + pidfile = fopen(name, "w"); + if (!pidfile) + return -1; + fprintf(pidfile, "%d\n", getpid()); + return fflush(pidfile); + } + return 0; +} + +int pidfile_refresh(void) +{ + if (pidfile) { + rewind(pidfile); + ftruncate(fileno(pidfile), 0); + fprintf(pidfile, "%d\n", getpid()); + return fflush(pidfile); + } + return 0; +} + +static void pidfile_close(void) +{ + if (pidfile) { + rewind(pidfile); + ftruncate(fileno(pidfile), 0); + fclose(pidfile); + pidfile = NULL; + } +} + +extern initcall_t __madinit[], __madexit[]; + +static void common_shutdown(void) { - extern initcall_t __madinit_start, __madinit_end; + pidfile_close(); - initcall_t *call_p = &__madinit_start; - while (call_p < &__madinit_end) { - (*call_p++)(); + for (int i = -1; __madexit[i]; i--) { + (*__madexit[i])(); } } -void common_shutdown(void) +static void __attribute__((__constructor__,__used__)) +common_initialize(void) { - extern exitcall_t __madexit_start, __madexit_end; + if (atexit(common_shutdown)) { + fputs("Cannot hook my atexit function, quitting !\n", stderr); + abort(); + } - exitcall_t *call_p = &__madexit_end; - while (call_p > &__madexit_start) { - (*--call_p)(); + for (int i = 0; __madinit[i]; i++) { + if ((*__madinit[i])()) { + exit(EXIT_FAILURE); + } } } +