daemon.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef TOOLS_ANDROID_FORWARDER2_DAEMON_H_
  5. #define TOOLS_ANDROID_FORWARDER2_DAEMON_H_
  6. #include <memory>
  7. #include <string>
  8. #include "base/macros.h"
  9. namespace forwarder2 {
  10. class Socket;
  11. // Provides a way to spawn a daemon and communicate with it.
  12. class Daemon {
  13. public:
  14. // Callback used by the daemon to shutdown properly. See pipe_notifier.h for
  15. // more details.
  16. typedef int (*GetExitNotifierFDCallback)();
  17. class ClientDelegate {
  18. public:
  19. virtual ~ClientDelegate() {}
  20. // Called after the daemon is ready to receive commands.
  21. virtual void OnDaemonReady(Socket* daemon_socket) = 0;
  22. };
  23. class ServerDelegate {
  24. public:
  25. virtual ~ServerDelegate() {}
  26. // Called after the daemon bound its Unix Domain Socket. This can be used to
  27. // setup signal handlers or perform global initialization.
  28. virtual void Init() = 0;
  29. virtual void OnClientConnected(std::unique_ptr<Socket> client_socket) = 0;
  30. };
  31. // |identifier| should be a unique string identifier. It is used to
  32. // bind/connect the underlying Unix Domain Socket.
  33. // Note that this class does not take ownership of |client_delegate| and
  34. // |server_delegate|.
  35. Daemon(const std::string& log_file_path,
  36. const std::string& identifier,
  37. ClientDelegate* client_delegate,
  38. ServerDelegate* server_delegate,
  39. GetExitNotifierFDCallback get_exit_fd_callback);
  40. ~Daemon();
  41. // Returns whether the daemon was successfully spawned. Note that this does
  42. // not necessarily mean that the current process was forked in case the daemon
  43. // is already running.
  44. bool SpawnIfNeeded();
  45. // Kills the daemon and blocks until it exited. Returns whether it succeeded.
  46. bool Kill();
  47. private:
  48. const std::string log_file_path_;
  49. const std::string identifier_;
  50. ClientDelegate* const client_delegate_;
  51. ServerDelegate* const server_delegate_;
  52. const GetExitNotifierFDCallback get_exit_fd_callback_;
  53. DISALLOW_COPY_AND_ASSIGN(Daemon);
  54. };
  55. } // namespace forwarder2
  56. #endif // TOOLS_ANDROID_FORWARDER2_DAEMON_H_