summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDiego Santa Cruz <Diego.SantaCruz@spinetix.com>2020-09-09 16:50:02 +0000
committerTobias Klauser <tobias.klauser@gmail.com>2020-09-10 11:58:14 +0200
commit8b834cd6928c573866627f41eacf2525d6211060 (patch)
tree93e831bddea45388aa53d1513f3179d4fa8e7626
parente496036b592c7c6d1bc419b5683a6a25bf46e193 (diff)
llmnrd: create pid file when daemonizing, and remove it on exit
The path of the pid file is /run/llmnrd/pid by default but can be changed via the PIDFILE make variable. Fixes #18 Signed-off-by: Diego Santa Cruz <Diego.SantaCruz@spinetix.com>
-rw-r--r--Makefile4
-rw-r--r--llmnrd.c37
2 files changed, 40 insertions, 1 deletions
diff --git a/Makefile b/Makefile
index b160b78..675535a 100644
--- a/Makefile
+++ b/Makefile
@@ -29,7 +29,9 @@ else
GIT_VERSION =
endif
-CFLAGS_MIN := -W -Wall -DVERSION_STRING=\"v$(VERSION)\" -DGIT_VERSION=\"$(GIT_VERSION)\"
+PIDFILE ?= /run/llmnrd/pid
+
+CFLAGS_MIN := -W -Wall -DVERSION_STRING=\"v$(VERSION)\" -DGIT_VERSION=\"$(GIT_VERSION)\" -DPIDFILE=\"$(PIDFILE)\"
ifeq ($(DEBUG), 1)
CFLAGS_MIN += -g -DDEBUG
endif
diff --git a/llmnrd.c b/llmnrd.c
index 1ea241f..81a5ac1 100644
--- a/llmnrd.c
+++ b/llmnrd.c
@@ -151,6 +151,37 @@ static void hostname_change_handle(char *hostname, size_t maxlen)
free(newname);
}
+static bool write_pid_file(void)
+{
+ int fd;
+ char buf[64];
+ ssize_t len;
+
+ fd = open(PIDFILE, O_CREAT|O_EXCL|O_RDWR, 0644);
+ if (fd == -1) {
+ log_err("Failed to open pid file %s: %s", PIDFILE, strerror(errno));
+ return false;
+ }
+
+ if (snprintf(buf, sizeof(buf), "%ji\n", (intmax_t) getpid()) < 0)
+ goto err;
+
+ len = strlen(buf);
+ if (write(fd, buf, len) != len)
+ goto err;
+
+ close(fd);
+ return true;
+
+err:
+ log_err("Failed to write pid to %s", PIDFILE);
+ if (fd != -1) {
+ unlink(PIDFILE);
+ close(fd);
+ }
+ return false;
+}
+
int main(int argc, char **argv)
{
int c, ret = -1;
@@ -160,6 +191,7 @@ int main(int argc, char **argv)
char *iface = NULL;
uint16_t port = LLMNR_UDP_PORT;
int llmnrd_sock_rtnl = -1;
+ bool rm_pid_file = false;
int nfds;
setlinebuf(stdout);
@@ -220,6 +252,9 @@ int main(int argc, char **argv)
log_err("Failed to daemonize process: %s\n", strerror(errno));
goto out;
}
+ if (!write_pid_file())
+ goto out;
+ rm_pid_file = true;
}
log_info("Starting llmnrd on port %u, hostname %s\n", port, hostname);
@@ -298,5 +333,7 @@ out:
if (llmnrd_sock_ipv4 >= 0)
close(llmnrd_sock_ipv4);
free(hostname);
+ if (rm_pid_file)
+ unlink(PIDFILE);
return ret == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
}