add session handling
authorPhilipp Gesang <philipp.gesang@intra2net.com>
Wed, 5 Jan 2022 15:38:15 +0000 (16:38 +0100)
committerPhilipp Gesang <philipp.gesang@intra2net.com>
Wed, 5 Jan 2022 15:42:16 +0000 (16:42 +0100)
The ``daemonize()`` API does not establish a new session so
processes that use it end up being controlled by the tty of the
process they were launched under, which too often happens to be
some system console.

src/daemonfunc.cpp
src/daemonfunc.hpp

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;
+}
+
 }
 }
index f6f77a3..f5b85cf 100644 (file)
@@ -38,6 +38,8 @@ bool drop_root_privileges(const std::string &username,
                           const std::string &group, bool get_group_from_user=false);
 
 bool pid_of(const std::string& name, std::vector< pid_t >& result);
+
+pid_t create_session (void);
 }
 }