forked from hy0kl/event-json-rpc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.c
119 lines (102 loc) · 2.2 KB
/
util.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
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#include "util.h"
int daemonize(int nochdir, int noclose)
{
int fd;
switch (fork())
{
case -1:
return (-1);
case 0:
break;
default:
_exit(EXIT_SUCCESS);
}
if (setsid() == -1)
return (-1);
if (nochdir == 0)
{
if(chdir("/") != 0)
{
perror("chdir");
return (-1);
}
}
if (noclose == 0 && (fd = open("/dev/null", O_RDWR, 0)) != -1)
{
if (dup2(fd, STDIN_FILENO) < 0)
{
perror("dup2 stdin");
return (-1);
}
if (dup2(fd, STDOUT_FILENO) < 0)
{
perror("dup2 stdout");
return (-1);
}
if (dup2(fd, STDERR_FILENO) < 0)
{
perror("dup2 stderr");
return (-1);
}
if (fd > STDERR_FILENO)
{
if (close(fd) < 0)
{
perror("close");
return (-1);
}
}
}
return(0);
}
static void signal_handler(int signo)
{
fprintf(stderr, "Get one signal: %d. man sigaction.\n", signo);
return;
}
void signal_setup(void)
{
static int signo[] = {
SIGHUP,
SIGINT, /* ctrl + c */
SIGCHLD, /* 僵死进程或线程的信号 */
SIGPIPE,
SIGALRM,
SIGUSR1,
SIGUSR2,
SIGTERM,
//SIGCLD,
#ifdef SIGTSTP
/* background tty read */
SIGTSTP,
#endif
#ifdef SIGTTIN
/* background tty read */
SIGTTIN,
#endif
#ifdef SIGTTOU
SIGTTOU,
#endif
SIGNO_END
};
int i = 0;
struct sigaction sa;
//sa.sa_handler = SIG_IGN; //设定接受到指定信号后的动作为忽略
sa.sa_handler = signal_handler;
sa.sa_flags = SA_SIGINFO;
if (-1 == sigemptyset(&sa.sa_mask)) //初始化信号集为空
{
fprintf(stderr, "failed to init sa_mask.\n");
exit(EXIT_FAILURE);
}
for (i = 0; SIGNO_END != signo[i]; i++)
{
//屏蔽信号
if (-1 == sigaction(signo[i], &sa, NULL))
{
fprintf(stderr, "failed to ignore: %d\n", signo[i]);
exit(EXIT_FAILURE);
}
}
return (void)0;
}