diff options
author | Tushar Pankaj <tushar.s.pankaj@gmail.com> | 2018-11-01 16:23:34 -0500 |
---|---|---|
committer | Tushar Pankaj <tushar.s.pankaj@gmail.com> | 2018-11-01 16:23:34 -0500 |
commit | 80aaa1112f2bf21f98be02f9e5f8be4bc7ed94d1 (patch) | |
tree | 68c24be090e0068236f187383bb2f22774cd827f | |
parent | Empty files for protocol code (diff) | |
download | wg-dynamic-80aaa1112f2bf21f98be02f9e5f8be4bc7ed94d1.tar.xz wg-dynamic-80aaa1112f2bf21f98be02f9e5f8be4bc7ed94d1.zip |
First draft of daemonize
Signed-off-by: Tushar Pankaj <tushar.s.pankaj@gmail.com>
-rw-r--r-- | daemonize.c | 56 | ||||
-rw-r--r-- | daemonize.h | 11 |
2 files changed, 67 insertions, 0 deletions
diff --git a/daemonize.c b/daemonize.c new file mode 100644 index 0000000..68ceb07 --- /dev/null +++ b/daemonize.c @@ -0,0 +1,56 @@ +/* SPDX-License-Identifier: MIT */ +/* + * Copyright (C) 2018 Wireguard LLC + */ + +#include <stdlib.h> +#include <unistd.h> +#include <sys/types.h> +#include <sys/stat.h> + +void daemonize(void) { + pid_t pid; + + /* fork */ + pid = fork(); + + /* check fork for error */ + if (pid < 0) { + perror("fork error"); + exit(EXIT_FAILURE); + } + + /* terminate the parent */ + if (pid > 0) { + exit(EXIT_SUCCESS); + } + + /* become session leader */ + if (setsid() < 0) { + perror("setsid error"); + exit(EXIT_FAILURE); + } + + /* fork */ + pid = fork(); + + /* check fork for error */ + if (pid < 0) { + perror("fork error"); + exit(EXIT_FAILURE); + } + + /* terminate the parent */ + if (pid > 0) { + exit(EXIT_SUCCESS); + } + + /* set up new environment */ + umask(S_IRWXG | S_IRWXO); /* umask 077 */ + chdir("/"); /* cd / to avoid locking up original cwd */ + + /* close file descriptors */ + for (int fd = sysconf(_SC_OPEN_MAX); fd >=0; fd--) { + close(fd); + } +} diff --git a/daemonize.h b/daemonize.h new file mode 100644 index 0000000..3720ff1 --- /dev/null +++ b/daemonize.h @@ -0,0 +1,11 @@ +/* SPDX-License-Identifier: MIT */ +/* + * Copyright (C) 2018 Wireguard LLC + */ + +#ifndef DAEMONIZE_H +#define DAEMONIZE_H + +void daemonize(void); + +#endif |