src: Making NLSR a daemon process with -d option

Change-Id: Ia9a83adab0140d918ce6c4adc2023dd43fc0fe8d
diff --git a/src/main.cpp b/src/main.cpp
index 36fc952..2497f74 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -42,7 +42,7 @@
         nlsr.setConfFileName(optarg);
         break;
       case 'd':
-        nlsr.setIsDaemonProcess(optarg);
+        nlsr.setIsDaemonProcess(true);
         break;
       case 'p':
       {
@@ -66,6 +66,9 @@
   INIT_LOGGERS(nlsr.getConfParameter().getLogDir());
   INIT_LOGGER("Main");
   nlsr.initialize();
+  if (nlsr.getIsSetDaemonProcess()) {
+    nlsr.daemonize();
+  }
   try {
     nlsr.startEventLoop();
   }
diff --git a/src/nlsr.cpp b/src/nlsr.cpp
index 5fef3bf..d4aa996 100644
--- a/src/nlsr.cpp
+++ b/src/nlsr.cpp
@@ -24,6 +24,7 @@
 #include <string>
 #include <sstream>
 #include <cstdio>
+#include <unistd.h>
 
 #include "nlsr.hpp"
 #include "adjacent.hpp"
@@ -87,6 +88,32 @@
 }
 
 void
+Nlsr::daemonize()
+{
+  pid_t process_id = 0;
+  pid_t sid = 0;
+  process_id = fork();
+  if (process_id < 0){
+    std::cerr << "Daemonization failed!" << std::endl;
+    throw Error("Error: Daemonization process- fork failed!");
+  }
+  if (process_id > 0) {
+    _LOG_DEBUG("Process daemonized. Process id: " << process_id);
+    exit(0);
+  }
+
+  umask(0);
+  sid = setsid();
+  if(sid < 0) {
+    throw Error("Error: Daemonization process- setting id failed!");
+  }
+
+  if (chdir("/") < 0) {
+    throw Error("Error: Daemonization process-chdir failed!");
+  }
+}
+
+void
 Nlsr::initialize()
 {
   _LOG_DEBUG("Initializing Nlsr");
diff --git a/src/nlsr.hpp b/src/nlsr.hpp
index fe1ef6c..b6b7ed6 100644
--- a/src/nlsr.hpp
+++ b/src/nlsr.hpp
@@ -328,6 +328,9 @@
   void
   setStrategies();
 
+  void
+  daemonize();
+
 private:
   void
   registerKeyPrefix();