diff options
| author | Joel Klinghed <the_jk@spawned.biz> | 2021-11-26 08:19:58 +0100 |
|---|---|---|
| committer | Joel Klinghed <the_jk@spawned.biz> | 2021-11-26 08:19:58 +0100 |
| commit | f70495a48646e54272783b4b709aca0396cb85f8 (patch) | |
| tree | 5e63b1f57582b3f025f1008034e4b066db0c32a6 /src/daemon.hh | |
| parent | 9c26f52e0942e3ddc8fe90fad5da871324c66f08 (diff) | |
Create daemon module and use it from server
Need to run setup() after forking, otherwise each TaskRunner created
in setup() will dead-lock at exit as there are now two copies of
each of them but not of the threads causing the destructors to lock.
This made setup a little bit more complicated as it has to forward
the log and status to parent process but I turned out quite nice.
Diffstat (limited to 'src/daemon.hh')
| -rw-r--r-- | src/daemon.hh | 45 |
1 files changed, 45 insertions, 0 deletions
diff --git a/src/daemon.hh b/src/daemon.hh new file mode 100644 index 0000000..10f0584 --- /dev/null +++ b/src/daemon.hh @@ -0,0 +1,45 @@ +#ifndef DAEMON_HH +#define DAEMON_HH + +#include <memory> + +class Logger; + +class Daemon { +public: + virtual ~Daemon() = default; + + // Method is called after forking; + // if it returns true then parent process will detach and return success and + // run is executed. + // if it returns false then parent process will exit in failure and run is + // never executed. + // Anything logged to logger will write to calling logger regardless of return + // value. + // Note that stdin, stdout and stderr are all closed when this runs, you + // must use logger object if you want to output anything. + // Current directory is not modified. + virtual bool setup(Logger* logger) = 0; + + // Method is called after forking and only after setup returns true. + // Note that stdin, stdout and stderr are all closed when this runs. + // Current directory is changed to root. + virtual bool run() = 0; + + // Forks, runs setup() method before returning true or false. + // If setup() returns true then so does this method and run() is called. + // If setup() returns false then so does this method and run() is never + // called. + static bool fork_in_background(Logger* logger, + std::unique_ptr<Daemon> daemon); + + // Doesn't fork, just runs setup() and if it returns true then + // also run() and waits for it to return. + static bool run_in_foreground(Logger* logger, + std::unique_ptr<Daemon> daemon); + +protected: + Daemon() = default; +}; + +#endif // DAEMON_HH |
