diff --git a/server/Makefile b/server/Makefile index 9db806f..f6e63f2 100644 --- a/server/Makefile +++ b/server/Makefile @@ -30,6 +30,7 @@ libjson-adapter.a: json-adapter.o registry.o nfc.o json_rpc.o \ security-token.o \ nfc_sets.o base64.o \ nulllogger.o \ + daemonize.o \ json_spirit/json_spirit_reader.o json_spirit/json_spirit_value.o json_spirit/json_spirit_writer.o ar rcs $@ $^ diff --git a/server/daemonize.cc b/server/daemonize.cc new file mode 100644 index 0000000..84e3eaa --- /dev/null +++ b/server/daemonize.cc @@ -0,0 +1,51 @@ +#include "daemonize.hh" + +// Unix/Linux implementation +#include +#include +#include +#include +#include + +#include + +void daemonize() +{ + /* already a daemon */ + if ( getppid() == 1 ) return; + + /* Fork off the parent process */ + pid_t pid = fork(); + if (pid < 0) + { + throw std::runtime_error("Cannot fork!"); + } + + if (pid > 0) + { + exit(EXIT_SUCCESS); /*Killing the Parent Process*/ + } + + /* At this point we are executing as the child process */ + + /* Create a new SID for the child process */ + pid_t sid = setsid(); + if (sid < 0) + { + throw std::runtime_error("Cannot call setsid()"); + } + + int fd = open("/dev/null",O_RDWR, 0); + + if (fd != -1) + { + dup2 (fd, STDIN_FILENO); + dup2 (fd, STDOUT_FILENO); + dup2 (fd, STDERR_FILENO); + + if (fd > 2) + { + close (fd); + } + } +} diff --git a/server/daemonize.hh b/server/daemonize.hh new file mode 100644 index 0000000..4e415f6 --- /dev/null +++ b/server/daemonize.hh @@ -0,0 +1,8 @@ +#ifndef JSON_SERVER_ADAPTER_DAEMONIZE_HH +#define JSON_SERVER_ADAPTER_DAEMONIZE_HH + +// fork(), go into background, close all ttys etc... +// system-specific! (POSIX, Windows, ...?) +void daemonize(); + +#endif