#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)
{
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])();
}
#define module_init(fn) static __init initcall_t __init_##fn = fn;
#define module_exit(fn) static __exit exitcall_t __exit_##fn = fn;
-/* common.c */
extern sig_atomic_t sigint;
extern sig_atomic_t sighup;
void common_sighandler(int sig);
-/* daemon.c */
int tcp_listen_nonblock(const struct sockaddr *addr, socklen_t len);
int accept_nonblock(int fd);
int daemon_detach(void);
int drop_privileges(const char *user, const char *group);
+int pidfile_open(const char *name);
+int pidfile_refresh(void);
+
#endif
int main(int argc, char *argv[])
{
const char *pidfile = NULL;
- FILE *f = NULL;
int res;
for (int c = 0; (c = getopt(argc, argv, "h" "p:")) >= 0; ) {
return EXIT_FAILURE;
}
- if (pidfile) {
- f = fopen(pidfile, "w");
- if (!f) {
- syslog(LOG_CRIT, "unable to write pidfile %s", pidfile);
- }
- fprintf(f, "%d\n", getpid());
- fflush(f);
+ if (pidfile_open(pidfile) < 0) {
+ syslog(LOG_CRIT, "unable to write pidfile %s", pidfile);
+ return EXIT_FAILURE;
}
if (daemon_detach() < 0) {
return EXIT_FAILURE;
}
- if (f) {
- rewind(f);
- ftruncate(fileno(f), 0);
- fprintf(f, "%d\n", getpid());
- fflush(f);
- }
+ pidfile_refresh();
res = main_loop();
- if (f) {
- rewind(f);
- ftruncate(fileno(f), 0);
- fclose(f);
- f = NULL;
- }
syslog(LOG_INFO, "Stopping...");
return res;
}
int port_dec = DEFAULT_DECODER_PORT;
const char *pidfile = NULL;
- FILE *f = NULL;
int res;
srs_t *srs;
return EXIT_FAILURE;
}
- if (pidfile) {
- f = fopen(pidfile, "w");
- if (!f) {
- syslog(LOG_CRIT, "unable to write pidfile %s", pidfile);
- }
- fprintf(f, "%d\n", getpid());
- fflush(f);
+ if (pidfile_open(pidfile) < 0) {
+ syslog(LOG_CRIT, "unable to write pidfile %s", pidfile);
+ return EXIT_FAILURE;
}
if (!unsafe && drop_privileges(RUNAS_USER, RUNAS_GROUP) < 0) {
return EXIT_FAILURE;
}
- if (f) {
- rewind(f);
- ftruncate(fileno(f), 0);
- fprintf(f, "%d\n", getpid());
- fflush(f);
- }
+ pidfile_refresh();
res = main_loop(srs, argv[optind], port_enc, port_dec);
- if (f) {
- rewind(f);
- ftruncate(fileno(f), 0);
- fclose(f);
- f = NULL;
- }
syslog(LOG_INFO, "Stopping...");
return res;
}