因此,使用 Visual Studio 创建 Windows 服务相当简单。我的问题更深入一点,即究竟是什么使可执行文件可作为服务安装以及如何将服务编写为直接的 C 应用程序。我找不到很多关于此的参考资料,但我假设必须有一些我可以实现的接口,以便我的 .exe 可以作为服务安装。
4 回答
Setting up your executable as a service is part of it, but realistically it's usually handled by whatever installation software you're using. You can use the command line SC tool while testing (or if you don't need an installer).
The important thing is that your program has to call StartServiceCtrlDispatcher() upon startup. This connects your service to the service control manager and sets up a ServiceMain routine which is your services main entry point.
ServiceMain (you can call it whatever you like actually, but it always seems to be ServiceMain) should then call RegisterServiceCtrlHandlerEx() to define a callback routine so that the OS can notify your service when certain events occur.
Here are some snippets from a service I wrote a few years ago:
set up as service:
SERVICE_TABLE_ENTRY ServiceStartTable[] =
{
{ "ServiceName", ServiceMain },
{ 0, 0 }
};
if (!StartServiceCtrlDispatcher(ServiceStartTable))
{
DWORD err = GetLastError();
if (err == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT)
return false;
}
ServiceMain:
void WINAPI ServiceMain(DWORD, LPTSTR*)
{
hServiceStatus = RegisterServiceCtrlHandlerEx("ServiceName", ServiceHandlerProc, 0);
service handler:
DWORD WINAPI ServiceHandlerProc(DWORD ControlCode, DWORD, void*, void*)
{
switch (ControlCode)
{
case SERVICE_CONTROL_INTERROGATE :
// update OS about our status
case SERVICE_CONTROL_STOP :
// shut down service
}
return 0;
}
基本上,您必须设置一些注册表设置以及要实现的一些接口。
看看这个:http: //msdn.microsoft.com/en-us/library/ms685141.aspx
您对 SCM(服务控制管理器)感兴趣。
我知道我参加聚会有点晚了,但我最近也有同样的问题,不得不在互联网上寻找答案。
我设法在 MSDN 中找到了这篇实际上奠定了基础的文章。我最终将这里的许多文件组合成一个包含我需要的所有命令的单个 exe,并添加了我自己的“void run()”方法,该方法在服务的整个生命周期中循环以满足我自己的需要。
对于有这个问题的其他人来说,这将是一个很好的开始,因此对于未来的搜索者,请查看:
完整的服务示例 http://msdn.microsoft.com/en-us/library/bb540476(VS.85).aspx