summaryrefslogtreecommitdiff
path: root/src/daemon.hh
blob: 10f0584714d0dd9d605a23f9418c914c8dc84964 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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