From dbe20017c0d84de216d5cc0e3163ceae5882ebc7 Mon Sep 17 00:00:00 2001 From: Tushar Pankaj Date: Thu, 1 Nov 2018 16:29:16 -0500 Subject: Add daemonize function to fork off as a daemon. Method: 1. Forks off 2. Becomes session leader 3. Forks off again 4. Sets up new environment 5. Closes all open file descriptors Squashed commit of the following: commit 1e71e5dcc6f979ce2f06d59e3c05660fa97e69f3 Author: Tushar Pankaj Date: Thu Nov 1 16:28:09 2018 -0500 Fix missing include in daemonize Signed-off-by: Tushar Pankaj commit 80aaa1112f2bf21f98be02f9e5f8be4bc7ed94d1 Author: Tushar Pankaj Date: Thu Nov 1 16:23:34 2018 -0500 First draft of daemonize Signed-off-by: Tushar Pankaj --- daemonize.c | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ daemonize.h | 11 +++++++++++ 2 files changed, 68 insertions(+) create mode 100644 daemonize.c create mode 100644 daemonize.h diff --git a/daemonize.c b/daemonize.c new file mode 100644 index 0000000..4f480e5 --- /dev/null +++ b/daemonize.c @@ -0,0 +1,57 @@ +/* SPDX-License-Identifier: MIT */ +/* + * Copyright (C) 2018 Wireguard LLC + */ + +#include +#include +#include +#include +#include + +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 -- cgit v1.2.3-59-g8ed1b