-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
135 lines (114 loc) · 2.5 KB
/
main.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
128
129
130
131
132
133
134
/*
* Udp proxy
*
* main.c
*
* Created on: Oct 14, 2015
* Modified on: Sep 01, 2016
* Author: igor.delac@gmail.com
*/
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <syslog.h>
#include <signal.h>
#include <getopt.h>
extern char *optarg;
extern int optind, opterr, optopt;
#include "usage.h"
#include "server.h"
void sighandler(int sig)
{
if (sig == SIGTERM)
{
syslog(LOG_NOTICE, "Service terminated.");
closelog();
exit(EXIT_SUCCESS);
}
}
int main(int argc, char **argv)
{
int c;
char* options = "l:s:p:hv";
char* argval[] = {NULL, NULL, NULL};
/*
* Parse arguments and their values.
*/
while ((c = getopt(argc, argv, options)) != -1)
{
switch (c)
{
case 'l':
argval[0] = optarg;
break;
case 's':
argval[1] = optarg;
break;
case 'p':
argval[2] = optarg;
break;
case 'h':
case 'v':
usage(argv[0]);
return EXIT_SUCCESS;
case '?':
printf("Unknown switch: %c. Ignoring.\n", optopt);
break;
default:
continue;
}
}
/*
* Check that argument values are set.
*/
if (argval[0] == NULL)
{
printf("Missing local udp port for listening.\n");
return EXIT_FAILURE;
}
if (argval[1] == NULL)
{
printf("Missing server ip address.\n");
return EXIT_FAILURE;
}
if (argval[2] == NULL)
{
printf("Missing server udp port number.\n");
return EXIT_FAILURE;
}
/*
* Start as service.
*/
pid_t pid;
pid = fork();
/* Error in fork. */
if (pid < 0)
{
return EXIT_FAILURE;
}
/* Terminate parent process. */
if (pid > 0)
{
return EXIT_SUCCESS;
}
/* Child process becomes session leader. */
if (setsid() < 0)
{
return EXIT_FAILURE;
}
/* Set new file permission */
umask(0);
/* Close file std. descriptors */
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
/* Install sig. handler for kill command (default signal is TERM) */
signal(SIGTERM, sighandler);
/* Open syslog logger */
openlog(argv[0], LOG_PID, LOG_DAEMON);
syslog(LOG_NOTICE, "Service started.");
/* Run main logic of udp proxy service. */
udpserver(argval[0], argval[1], argval[2]);
return EXIT_SUCCESS;
}