29
29
#include < sys/stat.h>
30
30
#include < pwd.h>
31
31
#include < grp.h>
32
+ #include < fcntl.h>
32
33
33
34
#include < RF24.h>
34
35
#include < MyGateway.h>
@@ -52,6 +53,8 @@ int pty_slave = -1;
52
53
static const mode_t ttyPermissions = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP;
53
54
static const char *serial_tty = _TTY_NAME;
54
55
static const char *devGroupName = _TTY_GROUPNAME;
56
+
57
+ int daemonizeFlag = 0 ;
55
58
/*
56
59
* handler for SIGINT signal
57
60
*/
@@ -93,6 +96,42 @@ void configure_master_fd(int fd)
93
96
tcsetattr (fd, 0 , &settings);
94
97
}
95
98
99
+ static void daemonize (void )
100
+ {
101
+ pid_t pid, sid;
102
+ int fd;
103
+
104
+ // already a daemon
105
+ if ( getppid () == 1 ) return ;
106
+
107
+ // Fork off the parent process
108
+ pid = fork ();
109
+ if (pid < 0 ) exit (EXIT_FAILURE); // fork() failed
110
+ if (pid > 0 ) exit (EXIT_SUCCESS); // fork() successful, this is the parent process, kill it
111
+
112
+ // From here on it is child only
113
+
114
+ // Create a new SID for the child process
115
+ sid = setsid ();
116
+ if (sid < 0 ) exit (EXIT_FAILURE); // Not logging as nobody can see it.
117
+
118
+ // Change the current working directory.
119
+ if ((chdir (" /" )) < 0 ) exit (EXIT_FAILURE);
120
+
121
+ // Divert the standard file desciptors to /dev/null
122
+ fd = open (" /dev/null" ,O_RDWR, 0 );
123
+ if (fd != -1 )
124
+ {
125
+ dup2 (fd, STDIN_FILENO);
126
+ dup2 (fd, STDOUT_FILENO);
127
+ dup2 (fd, STDERR_FILENO);
128
+
129
+ if (fd > 2 ) close (fd);
130
+ }
131
+
132
+ // reset File Creation Mask
133
+ umask (027 );
134
+ }
96
135
97
136
/*
98
137
* Main gateway logic
@@ -104,8 +143,18 @@ int main(int argc, char **argv)
104
143
105
144
MyGateway *gw = NULL ;
106
145
int status = EXIT_SUCCESS;
107
- int ret;
108
-
146
+ int ret, c;
147
+
148
+ while ((c = getopt (argc, argv, " d" )) != -1 )
149
+ {
150
+ switch (c)
151
+ {
152
+ case ' d' :
153
+ daemonizeFlag = 1 ;
154
+ break ;
155
+ }
156
+ }
157
+
109
158
printf (" Starting PiGatewaySerial...\n " );
110
159
printf (" Protocol version - %s\n " , LIBRARY_VERSION);
111
160
@@ -174,7 +223,7 @@ int main(int argc, char **argv)
174
223
175
224
fds.events = POLLRDNORM;
176
225
fds.fd = pty_master;
177
-
226
+ if (daemonizeFlag) daemonize ();
178
227
/* we are ready, initialize the Gateway */
179
228
gw->begin (RF24_PA_LEVEL_GW, RF24_CHANNEL, RF24_DATARATE, &write_msg_to_pty);
180
229
0 commit comments