forked from hoterran/tcpcollect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.c
127 lines (108 loc) · 2.79 KB
/
utils.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
119
120
121
122
123
124
125
126
127
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <libgen.h>
#include <signal.h>
#include <stdint.h>
#include <stdarg.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include "utils.h"
#include "log.h"
#include "stat.h"
void _Assert (char* name, char* strFile, unsigned uLine)
{
dump(L_ERR, "Assertion failed: %s, %s, line %u", name, strFile, uLine);
printPacketInfo();
abort();
}
int daemon_init(void)
{
pid_t pid;
if((pid = fork())< 0) {
return ERR;
} else if(pid > 0) {
dump(L_ERR, "parent process exit.");
exit(0);
}
setsid();
if((pid = fork()) < 0) {
return ERR;
} else if(pid > 0) {
dump(L_INFO, "child process exit.");
exit(0);
}
dump(L_INFO, "Daemon Start Working.");
umask(0);
return OK;
}
/* for single process */
int lock_fd;
int single_process(char *process_name)
{
char lockfile[128];
snprintf(lockfile, sizeof(lockfile), "/var/lock/%s.pid", basename(process_name));
lock_fd = open(lockfile, O_CREAT|O_WRONLY, 00200);
if (lock_fd <= 0) {
dump(L_ERR, "Cant fopen file %s for %s\n", lockfile, strerror(errno));
return -1;
}
/* F_LOCK will hang until unlock, F_TLOCK will return asap */
int ret = lockf(lock_fd, F_TLOCK, 0);
if (ret == 0) {
return 0;
} else {
dump(L_ERR, "Cant lock %s for %s\n", lockfile, strerror(errno));
return -1;
}
}
void sig_pipe_handler(int sig) {
return;
}
void
select_sleep(unsigned int second)
{
if (second <= 0)
return ;
struct timeval t_timeval;
t_timeval.tv_sec = second;
t_timeval.tv_usec = 0;
while(1)
{
if ((t_timeval.tv_sec == 0)&&(t_timeval.tv_usec == 0))//for eintr
{
break;
}
select(0, NULL, NULL, NULL, &t_timeval);
}
}
void sig_init(void)
{
/*
* block
* SIGTERM SIGHUP SIGPIPE
*
* handler
* SIGALRM
*/
sigset_t intmask;
sigemptyset(&intmask);
sigaddset(&intmask,SIGTERM);
sigprocmask(SIG_BLOCK,&intmask,NULL);
sigemptyset(&intmask);
sigaddset(&intmask,SIGHUP);
sigprocmask(SIG_BLOCK,&intmask,NULL);
struct sigaction act2;
act2.sa_handler = sig_pipe_handler;
act2.sa_flags = SA_INTERRUPT;
sigemptyset(&act2.sa_mask);
sigaddset(&act2.sa_mask, SIGPIPE);
sigaction(SIGPIPE, &act2, 0);
}