X-Git-Url: http://git.madism.org/?a=blobdiff_plain;ds=sidebyside;f=common.c;h=d3147ffc82c7bdd36a66bc4d12a70838fb8f7253;hb=c78538ac1dd1f22e4b6384b6e85a153646cb90d9;hp=80746ae554b80faef68821938315044211b022a0;hpb=dbc6818c72dfe618b164db970773490b19b808c5;p=apps%2Fpfixtools.git diff --git a/common.c b/common.c index 80746ae..d3147ff 100644 --- a/common.c +++ b/common.c @@ -40,8 +40,10 @@ #include "common.h" -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) { @@ -204,9 +206,52 @@ int drop_privileges(const char *user, const char *group) return 0; } +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[]; -void common_initialize(void) +static void common_shutdown(void) +{ + pidfile_close(); + + for (int i = -1; __madexit[i]; i--) { + (*__madexit[i])(); + } +} + +static void __attribute__((__constructor__,__used__)) +common_initialize(void) { if (atexit(common_shutdown)) { fputs("Cannot hook my atexit function, quitting !\n", stderr); @@ -220,9 +265,3 @@ void common_initialize(void) } } -void common_shutdown(void) -{ - for (int i = -1; __madexit[i]; i--) { - (*__madexit[i])(); - } -}