summaryrefslogtreecommitdiffstats
path: root/common/sys/daemon.c
blob: 829d0a9c7a3b2f7a3faec630f26be823efcc9cff (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
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
85
86
87
88
89
90
/* $Id$ */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>

#include "osdep.h"
#include "cmsys.h"

int
daemonize(const char * pidfile, const char * logfile)
{
    int fd;
    char buf[32];
    pid_t pid;

    umask(022);

    if ((pid = fork()) < 0) {
    perror("Fork failed");
    exit(1);
    }

    if (pid > 0)
    exit(0);

    if (setsid() < 0) {
    perror("Setsid failed");
    exit(-1);
    }

    if ((pid = fork()) < 0) {
    perror("Fork failed");
    exit(1);
    }

    if (pid > 0)
    exit(0);

    if (chdir("/") < 0) {
    perror("Can't chdir to root");
    exit(-1);
    }

    if (pidfile) {
    if ((fd = creat(pidfile, 0644)) >= 0) {
        snprintf(buf, sizeof(buf), "%d", (int)getpid());
        write(fd, buf, strlen(buf));
        close(fd);
    } else
        perror("Can't open PID file");
    }

    if (logfile) {
    if ((fd = open(logfile, O_WRONLY | O_CREAT | O_APPEND, 0644)) < 0) {
        perror("Can't open logfile");
        exit(1);
    }
    if (fd != 2) {
        dup2(fd, 2);
        close(fd);
    }
    }

    fd = getdtablesize();
    while (fd > 2)
    close(--fd);

    if ((fd = open("/dev/null", O_RDWR)) < 0) {
    perror("Can't open /dev/null");
    exit(1);
    }

    dup2(fd, 0);
    dup2(fd, 1);
    if (!logfile)
    dup2(fd, 2);

    if (fd > 2)
    close(fd);

    Signal(SIGHUP, SIG_IGN);
    Signal(SIGCHLD, SIG_IGN);

    return 0;
}