RCFProto
 All Classes Functions Typedefs
NtService.hpp
1 
2 //******************************************************************************
3 // RCF - Remote Call Framework
4 //
5 // Copyright (c) 2005 - 2013, Delta V Software. All rights reserved.
6 // http://www.deltavsoft.com
7 //
8 // RCF is distributed under dual licenses - closed source or GPL.
9 // Consult your particular license for conditions of use.
10 //
11 // If you have not purchased a commercial license, you are using RCF
12 // under GPL terms.
13 //
14 // Version: 2.0
15 // Contact: support <at> deltavsoft.com
16 //
17 //******************************************************************************
18 
19 #ifndef INCLUDE_UTIL_NTSERVICE_HPP
20 #define INCLUDE_UTIL_NTSERVICE_HPP
21 
22 #include <Windows.h>
23 #include <fstream>
24 
25 #include <RCF/util/Tchar.hpp>
26 
27 namespace RCF {
28 
29  class NtService
30  {
31  public:
32 
33  NtService(
34  const std::string & serviceName,
35  const std::string & serviceDisplayName);
36 
37  virtual ~NtService()
38  {}
39 
40  int RunAsServiceOrInteractive();
41  void SetServiceStatus(DWORD dwState, DWORD waitHint = 0);
42  bool Install();
43  bool Install(const tstring & commandLineArgs);
44  bool Uninstall();
45  bool IsInstalled() const;
46 
47  private:
48 
49  void ServiceMain(DWORD dwArgc, LPTSTR * lpszArgv);
50 
51  virtual int Start() = 0;
52  virtual void Handler(DWORD dwOpcode);
53 
54  friend static void WINAPI _ServiceMain(DWORD dwArgc, LPTSTR* lpszArgv);
55  friend static void WINAPI _Handler(DWORD dwOpcode);
56  static NtService * spThis;
57 
58  protected:
59 
60  std::string mServiceName;
61  std::string mServiceDisplayName;
62 
63  SERVICE_STATUS_HANDLE mhServiceStatus;
64  SERVICE_STATUS mStatus;
65 
66  volatile bool mStopFlag;
67  bool mRunningAsService;
68  std::ofstream mLog;
69  };
70 
71 } // namespace RCF
72 
73 #endif // ! INCLUDE_UTIL_NTSERVICE_HPP
74 
75 // Sample usage.
76 /*
77 #include <RCF/util/NtService.hpp>
78 
79 #include <RCF/util/../../../src/RCF/util/NtService.cpp>
80 
81 class MyService : public RCF::NtService
82 {
83 public:
84 
85  MyService() : RCF::NtService("MyService", "My Really Useful Service")
86  {
87  }
88 
89  void Start()
90  {
91  std::ofstream fout("c:\\serviceOut.log");
92  int n = 0;
93  while (!mStopFlag)
94  {
95  fout << ++n << std::endl;
96  Sleep(1000);
97  }
98  }
99 };
100 
101 MyService gService;
102 
103 int main(int argc, char ** argv)
104 {
105  bool install = false;
106  bool uninstall = false;
107 
108  // TODO: parse the command line args.
109  // ...
110 
111  if (install)
112  {
113  gService.Install();
114  return 0;
115  }
116  else if (uninstall)
117  {
118  gService.Uninstall();
119  return 0;
120  }
121 
122  gService.RunAsServiceOrInteractive();
123  return 0;
124 }
125 */