安装和卸载服务
服务的安装由 CNTService::Install 处理,它用 Win32 服务管理器注册服务并在注册表中建立一个条目以支持服务运行时日志消息。
服务的卸载由 CNTService::Uninstall 处理,它仅仅通知服务管理器该服务已经不再需要。CNTService::Uninstall 不会删除服务实际的可执行文件。 逆@风@者
编写服务代码
现在我们来编写实现服务的具体代码。对于 NTService 例子,有三个函数要写。他们涉及初始化,运行服务的细节和响应控制请求。
初始化
注册表有一个给服务用来存储参数的地方:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services
我就是选择这里来存储我的服务配置信息。我创建了一个 Parameters 键,并在此存储我要保存的值。所以当服务启动时,OnInit 函数被调用;这个函数从注册表中读取初始设置。
BOOL CMyService::OnInit()
{
// Read the registry parameters.
// Try opening the registry key:
// HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\\Parameters
HKEY hkey;
char szKey[1024];
strcpy(szKey, "SYSTEM\\CurrentControlSet\\Services\\");
strcat(szKey, m_szServiceName);
strcat(szKey, "\\Parameters");
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE,
szKey,
0,
KEY_QUERY_VALUE,
&hkey) == ERROR_SUCCESS) {
// Yes we are installed.
DWORD dwType = 0;
DWORD dwSize = sizeof(m_iStartParam);
RegQueryValueEx(hkey,
"Start",
NULL,
&dwType,
(BYTE*)&m_iStartParam,
&dwSize);
dwSize = sizeof(m_iIncParam);
RegQueryValueEx(hkey,
"Inc",
NULL,
&dwType,
(BYTE*)&m_iIncParam,
&dwSize);
RegCloseKey(hkey);
}
// Set the initial state.
m_iState = m_iStartParam;
return TRUE;
}
现在我们有了服务参数,我们便可以运行服务了。
运行服务
当 Run 函数被调用时将执行服务的主体代码。本文例子的这部分很简单:
void CMyService::Run()
{
while (m_bIsRunning) {
// Sleep for a while.
DebugMsg("My service is sleeping (%lu)...", m_iState);
Sleep(1000);
// Update the current state.
m_iState = m_iIncParam;
}
}
注意,只要服务不终止,这个函数就不会退出。当有终止服务的请求时,CNTService::m_bIsRunning 标志被置成 FALSE。如果在服务终止时,你要实现清除操作,那么你还可以改写 OnStop 和/或 OnShutdown。
响应控制请求
你可以用任何适合的方式与服务通讯——命名管道,思想交流,便条等等——对于一些简单的请求,用系统函数 ControlService 很容易实现。CNTService 提供了一个处理器专门用于通过 ControlService 函数发送的非标准消息(也就是用户发送的消息)。本文例子用单一消息在注册表中保存当前服务的状态,以便其它应用程序能看到它。我不建议用这种方法来监控服务,因为它不是最佳方法,这只是比较容易编码实现而已。 本文章更多内容:<<上一页 - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 下一页>> |