-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdaemon.c
78 lines (61 loc) · 1.17 KB
/
daemon.c
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
/*
* Copyright Tian Hao <[email protected]>
* License: GPLv3
* It is an opensource (free) software
*/
#define _POSIX_C_SOURCE 200809L
#define _XOPEN_SOURCE 700
#include <unistd.h>
#include <signal.h>
#include <sys/signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <stdlib.h>
#define CTLTERM "/dev/tty"
#include "daemon.h"
#include "tools.h"
static int __daemon()
{
int fd0, fd1, fd2;
pid_t pid;
struct sigaction sa;
umask(0);
if((pid = fork()) < 0)
return -1;
else if(pid > 0)
exit(0);
if(setsid() < 0)
return -1;
sa.sa_handler = SIG_IGN;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
if(sigaction(SIGHUP, &sa, NULL) < 0)
return -1;
if((pid = fork()) < 0)
return -1;
else if(pid > 0)
exit(0);
if(chdir("/") < 0)
return -1;
for(int i = 0; i < 1024 ; i++)
close(i);
fd0 = open("/dev/null", O_RDWR);
fd1 = dup(fd0);
fd2 = dup(fd0);
if((fd0 != STDIN_FILENO) || (fd1 != STDOUT_FILENO) || (fd2 != STDERR_FILENO)) {
close(fd0);
close(fd1);
close(fd2);
return -1;
}
return 0;
}
void do_daemon()
{
if (__daemon() < 0) {
mydm_print("Can not initialize daemon\n");
exit(1);
}
}