summaryrefslogtreecommitdiff
path: root/daemon.c
diff options
context:
space:
mode:
authorMikhail Osipov <mike.osipov@gmail.com>2019-10-18 17:43:38 +0300
committerMikhail Osipov <mike.osipov@gmail.com>2019-10-18 17:43:38 +0300
commit3b00c7be0e8834402ed93eb42b3a93302076c5ff (patch)
treeebf1643f00d2206c80676b1057f6d42d494d5c3a /daemon.c
parent9c05f1c4187de3c43c027f6102b6e161b2f7441c (diff)
skel
Diffstat (limited to 'daemon.c')
-rw-r--r--daemon.c74
1 files changed, 74 insertions, 0 deletions
diff --git a/daemon.c b/daemon.c
new file mode 100644
index 0000000..305755d
--- /dev/null
+++ b/daemon.c
@@ -0,0 +1,74 @@
+#include <sys/socket.h>
+#include <stdlib.h>
+#include <signal.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <err.h>
+
+#include "tunnel.h"
+#include "macro.h"
+
+static void sighandler(int signo __unused)
+{
+ unlink(TUNNEL_SOCK_PATH);
+ exit(EXIT_FAILURE);
+}
+
+static void tunnel_daemon_loop(int sock)
+{
+ for (;;) {
+ int fd = accept(sock, NULL, NULL);
+ if (fd < 0) {
+ warn("accept");
+ continue;
+ }
+
+ FILE *fp = fdopen(fd, "w");
+ if (fp) {
+ fprintf(fp, "hello from %d", getpid());
+ fclose(fp);
+ }
+ }
+}
+
+int tunnel_daemon(int sock)
+{
+ switch (fork()) {
+ case -1:
+ warn("fork");
+ return -1;
+ case 0:
+ break;
+ default:
+ return 0;
+ }
+
+ if (setsid() < 0)
+ err(EXIT_FAILURE, "setsid");
+
+ chdir("/");
+
+ struct sigaction sa = {
+ .sa_handler = sighandler
+ };
+
+ sigaction(SIGTERM, &sa, NULL);
+ sigaction(SIGINT, &sa, NULL);
+
+#if 0
+ int fd = open("/dev/null", O_RDWR);
+ if (fd < 0)
+ err(EXIT_FAILURE, "open /dev/null");
+
+ dup2(fd, STDIN_FILENO);
+ dup2(fd, STDOUT_FILENO);
+ dup2(fd, STDERR_FILENO);
+
+ if (fd > 2)
+ close(fd);
+#endif
+
+ tunnel_daemon_loop(sock);
+
+ return 0;
+}