From 478afd5eb545d5ae0ecbfc2c9f216111f559fefe Mon Sep 17 00:00:00 2001 From: Philipp Gesang Date: Wed, 5 Jan 2022 16:38:15 +0100 Subject: [PATCH] add session handling 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 | 27 +++++++++++++++++++++++++++ src/daemonfunc.hpp | 2 ++ 2 files changed, 29 insertions(+), 0 deletions(-) diff --git a/src/daemonfunc.cpp b/src/daemonfunc.cpp index 248a79b..6481493 100644 --- a/src/daemonfunc.cpp +++ b/src/daemonfunc.cpp @@ -25,6 +25,8 @@ on this file might be covered by the GNU General Public License. #include #include #include +#include +#include #include #include @@ -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; +} + } } diff --git a/src/daemonfunc.hpp b/src/daemonfunc.hpp index f6f77a3..f5b85cf 100644 --- a/src/daemonfunc.hpp +++ b/src/daemonfunc.hpp @@ -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); } } -- 1.7.1