post
poster: jsaxton
description: Spawns a daemon
language: C
[download]
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<sys/wait.h>
#include<unistd.h>
#include<errno.h>
#include<fcntl.h>

int daemonize();

int main() {
    daemonize();
    while(1) {
        sleep(5);
    }
    return 0;
}

//This function turns the process into a daemon
//It returns 1 upon success
//It returns -1 upon failure
int daemonize() {
    pid_t childpid;
    int fd;

    //Set umask to 0
    umask(0);

    //call fork and have the parent exit
    childpid = fork();
    if(childpid == -1) {
        perror("Failed to fork");
        return -1;
    }
    if(childpid == 0) {
        //This code was taken from Unix Systems Programming by Robbins
        //Example 8.5
        if(kill(getppid(), SIGTERM) == -1) {
            perror("Failed to kill parent");
            return -1;
        }
    }
    if(childpid > 0) {
        //We should wait for the child to kill us
        waitpid(childpid, NULL,0);
    }

    //create a new session
    if(setsid() == -1) {
        perror("Failed to become session leader");
        return -1;
    }

    //change cwd to /
    char *directory = "/";
    if(chdir("/") == -1) {
        perror("Failed to change current working directory to /");
        return -1;
    }

    //redirect 0, 1 and 2 to /dev/null
    fd = open("/dev/null", O_RDWR);
    if(fd == -1) {
        perror("Failed to open /dev/null");
        return -1;
    }

    if(dup2(fd, STDOUT_FILENO) == -1) {
        perror("Failed to redirect stdout");
        return -1;
    }

    if(dup2(fd, STDIN_FILENO) == -1) {
        perror("Failed to redirect stdin");
        return -1;
    }

    if(dup2(fd, STDERR_FILENO) == -1) {
        perror("Failed to redirect stderr");
        return -1;
    }

    return 1;
}