-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdaemonize.cpp
More file actions
71 lines (56 loc) · 1.59 KB
/
Copy pathdaemonize.cpp
File metadata and controls
71 lines (56 loc) · 1.59 KB
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
/*
* Adapted from
* http://www-theorie.physik.unizh.ch/~dpotter/howto/daemonize
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "daemonize.h"
namespace isaword {
/**
* Forks off the current process as a daemon.
* @param log_file file to log stdout and stderr to.
* May be NULL to indicate no logging.
* @return result of fork(): positive PID in for the
* parent process, 0 for the child process, a negative
* PID in case of failure.
*/
pid_t daemonize(const char* log_file) {
pid_t sid;
/* already a daemon */
if ( getppid() == 1 ) return -1;
/* Fork off the parent process */
pid_t pid = fork();
if (pid < 0) {
return pid;
}
/* If we got a good PID, then we can exit the parent process. */
if (pid > 0) {
return pid;
}
/* At this point we are executing as the child process */
/* Change the file mode mask */
umask(0);
/* Create a new SID for the child process */
sid = setsid();
if (sid < 0) {
return sid;
}
/* Change the current working directory. This prevents the current
directory from being locked; hence not being able to remove it. */
if ((chdir("/")) < 0) {
return -1;
}
/* Redirect standard files to proper loging output. */
const char* outfile = log_file;
if (outfile == NULL) {
outfile = "/dev/null";
}
freopen( "/dev/null", "r", stdin);
freopen( outfile, "w", stdout);
freopen( outfile, "w", stderr);
return 0;
}
} /* namespace isaword */