-
Notifications
You must be signed in to change notification settings - Fork 1
/
lexidest.cpp
104 lines (88 loc) · 2.71 KB
/
lexidest.cpp
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include <dirent.h>
#include <iterator>
#include <cstdlib>
#include <cstring>
#include <sstream>
#include <iostream>
#include <stdlib.h>
#include <string>
#include <sys/stat.h>
#include <syslog.h>
#include <unistd.h>
#include <vector>
bool fileExists(const std::string& file) {
struct stat buf;
return (stat(file.c_str(), &buf) == 0);
}
void do_heartbeat()
{
std::string lockfile = "/tmp/lexilock";
if(!fileExists(lockfile)){
system("~/.lexidest/script.sh");
}
}
// For security purposes, we don't allow any arguments to be passed into the daemon
int main(void)
{
// Define variables
pid_t pid, sid;
// Fork the current process
pid = fork();
// The parent process continues with a process ID greater than 0
if(pid > 0)
{
exit(EXIT_SUCCESS);
}
// A process ID lower than 0 indicates a failure in either process
else if(pid < 0)
{
exit(EXIT_FAILURE);
}
// The parent process has now terminated, and the forked child process will continue
// (the pid of the child process was 0)
// Since the child process is a daemon, the umask needs to be set so files and logs can be written
umask(0);
// Open system logs for the child process
openlog("Lexidest", LOG_NOWAIT | LOG_PID, LOG_USER);
syslog(LOG_NOTICE, "Successfully started Lexidest");
// Generate a session ID for the child process
sid = setsid();
// Ensure a valid SID for the child process
if(sid < 0)
{
// Log failure and exit
syslog(LOG_ERR, "Could not generate session ID for child process");
// If a new session ID could not be generated, we must terminate the child process
// or it will be orphaned
exit(EXIT_FAILURE);
}
// Change the current working directory to a directory guaranteed to exist
if((chdir("/")) < 0)
{
// Log failure and exit
syslog(LOG_ERR, "Could not change working directory to /");
// If our guaranteed directory does not exist, terminate the child process to ensure
// the daemon has not been hijacked
exit(EXIT_FAILURE);
}
// A daemon cannot use the terminal, so close standard file descriptors for security reasons
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
// Daemon-specific intialization should go here
const int SLEEP_INTERVAL = 1;
system("rm -rf /tmp/lexilock");
// Enter daemon loop
while(1)
{
// Execute daemon heartbeat, where your recurring activity occurs
do_heartbeat();
// Sleep for a period of time
sleep(SLEEP_INTERVAL);
}
// Close system logs for the child process
syslog(LOG_NOTICE, "Stopping Lexidest");
closelog();
// Terminate the child process when the daemon completes
exit(EXIT_SUCCESS);
}