X-Git-Url: http://git.madism.org/?a=blobdiff_plain;f=common.c;h=186ac43abf98d20c52149ac017e605fb86a12dff;hb=4c619131857a40cf59a472fc55257bae4ded12d7;hp=7553779db48e6455132e3f73756451e60c7b733c;hpb=59b31c88179af4a9a9c9074a7b428841ce8661f8;p=apps%2Fpfixtools.git diff --git a/common.c b/common.c index 7553779..186ac43 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) { @@ -157,6 +159,20 @@ int accept_nonblock(int fd) return sock; } +int xwrite(int fd, const char *s, size_t l) +{ + while (l > 0) { + int nb = write(fd, s, l); + if (nb < 0) { + if (errno == EINTR || errno == EAGAIN) + continue; + return -1; + } + l -= nb; + } + return 0; +} + int daemon_detach(void) { pid_t pid; @@ -204,10 +220,45 @@ 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[]; static void common_shutdown(void) { + pidfile_close(); + for (int i = -1; __madexit[i]; i--) { (*__madexit[i])(); }