c++ windows服务,当服务停止时,将停止信息写入日志
时间: 2024-01-05 14:03:12 浏览: 31
在 C++ 中,可以使用 Windows API 来编写 Windows 服务。当服务停止时,可以使用 `ReportEvent()` 函数将停止信息写入 Windows 日志。
下面是一个简单的示例:
```c++
#include <windows.h>
#include <stdio.h>
#define SERVICE_NAME "MyService"
SERVICE_STATUS g_ServiceStatus = {0};
SERVICE_STATUS_HANDLE g_StatusHandle = NULL;
HANDLE g_ServiceStopEvent = INVALID_HANDLE_VALUE;
void WriteToLog(const char* pszMessage) {
HANDLE hEventSource = NULL;
LPCSTR lpszStrings[2] = {NULL, NULL};
hEventSource = RegisterEventSource(NULL, SERVICE_NAME);
if (hEventSource) {
lpszStrings[0] = SERVICE_NAME;
lpszStrings[1] = pszMessage;
ReportEvent(hEventSource, // event log handle
EVENTLOG_INFORMATION_TYPE, // event type
0, // event category
0, // event ID
NULL, // current user's SID
2, // strings in lpszStrings
0, // no bytes of raw data
lpszStrings, // array of strings
NULL); // no raw data
DeregisterEventSource(hEventSource);
}
}
void WINAPI ServiceMain(DWORD argc, LPSTR* argv);
void WINAPI ServiceCtrlHandler(DWORD);
void StartService();
void StopService();
int main(int argc, char* argv[]) {
SERVICE_TABLE_ENTRY ServiceTable[] = {
{SERVICE_NAME, (LPSERVICE_MAIN_FUNCTION)ServiceMain},
{NULL, NULL}
};
if (StartServiceCtrlDispatcher(ServiceTable) == FALSE) {
return GetLastError();
}
return 0;
}
void WINAPI ServiceMain(DWORD argc, LPSTR* argv) {
DWORD Status = E_FAIL;
g_StatusHandle = RegisterServiceCtrlHandler(SERVICE_NAME, ServiceCtrlHandler);
if (g_StatusHandle == NULL) {
return;
}
g_ServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
g_ServiceStatus.dwServiceSpecificExitCode = 0;
SetServiceStatus(g_StatusHandle, &g_ServiceStatus);
StartService();
WaitForSingleObject(g_ServiceStopEvent, INFINITE);
StopService();
g_ServiceStatus.dwCurrentState = SERVICE_STOPPED;
SetServiceStatus(g_StatusHandle, &g_ServiceStatus);
}
void WINAPI ServiceCtrlHandler(DWORD CtrlCode) {
switch (CtrlCode) {
case SERVICE_CONTROL_STOP:
g_ServiceStatus.dwCurrentState = SERVICE_STOP_PENDING;
SetServiceStatus(g_StatusHandle, &g_ServiceStatus);
SetEvent(g_ServiceStopEvent);
break;
default:
break;
}
}
void StartService() {
g_ServiceStopEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (g_ServiceStopEvent == NULL) {
WriteToLog("Could not create service stop event.");
return;
}
g_ServiceStatus.dwCurrentState = SERVICE_RUNNING;
SetServiceStatus(g_StatusHandle, &g_ServiceStatus);
WriteToLog("MyService started.");
}
void StopService() {
WriteToLog("MyService stopped.");
if (g_ServiceStopEvent != NULL) {
CloseHandle(g_ServiceStopEvent);
g_ServiceStopEvent = NULL;
}
}
```
在上面的例子中,`WriteToLog()` 函数使用 `RegisterEventSource()` 函数注册一个 Windows 日志事件源,并使用 `ReportEvent()` 函数将事件写入日志。在服务停止时,`StopService()` 函数调用 `WriteToLog()` 函数写入停止信息。
注意:在使用 `RegisterEventSource()` 函数注册事件源时,需要管理员权限才能成功。