add session handling
[libi2ncommon] / src / daemonfunc.cpp
index 248a79b..6481493 100644 (file)
@@ -25,6 +25,8 @@ on this file might be covered by the GNU General Public License.
 #include <stdlib.h>
 #include <pwd.h>
 #include <grp.h>
+#include <errno.h>
+#include <string.h>
 
 #include <string>
 #include <stdexcept>
@@ -227,5 +229,30 @@ bool pid_of(const std::string& name, std::vector< pid_t >& result)
    return true;
 } // eo pidOf(const std::string&,std::vector< pid_t >&)
 
+/**
+ * @brief   establish a new session for the current process.
+ *
+ * @return  the id of the new session.
+ *
+ * This wraps setsid(2); to be called from a child process after forking.
+ * Raises ``runtime_error`` if the call fails.
+ */
+pid_t create_session (void)
+{
+    pid_t sid;
+
+    errno = 0;
+    if ((sid = setsid ()) == -1)
+    {
+        throw std::runtime_error
+            ((std::string)
+             "create_session: setsid() returned an error ("
+             + I2n::to_string (errno)
+             + "): " + strerror (errno));
+    }
+
+    return sid;
+}
+
 }
 }