aboutsummaryrefslogtreecommitdiffstats
path: root/daemonize.c
blob: 4f480e5aa96d238308ca84307fb2d5a3c65082a1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/* SPDX-License-Identifier: MIT */
/*
 * Copyright (C) 2018 Wireguard LLC
 */

#include <stdio.h>
#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);
    }
}