我使用https://msdn.microsoft.com/en-us/library/bb540476(VS.85).aspx上的完整示例为Windows创建了一项服务。
我不知道这是不是最好的例子。很多人说微软的例子不是最好的。但它的确有效。我可以毫无问题地安装,启动,停止和删除服务。
但是现在我需要有效地将代码的一部分放在服务将要做的事情上。
阅读代码我理解这部分创建了一个列表,并在其中放置了服务的主要部分:
// TO_DO: Add any additional services for the process to this table.
SERVICE_TABLE_ENTRY DispatchTable[] =
{
{ SVCNAME, (LPSERVICE_MAIN_FUNCTION) SvcMain },
{ NULL, NULL }
};
// This call returns when the service has stopped.
// The process should simply terminate when the call returns.
if (!StartServiceCtrlDispatcher( DispatchTable ))
{
SvcReportEvent(TEXT("StartServiceCtrlDispatcher"));
}
如果我在服务启动时正确理解,将执行SvcMain功能。
// Purpose:
// Entry point for the service
//
// Parameters:
// dwArgc - Number of arguments in the lpszArgv array
// lpszArgv - Array of strings. The first string is the name of
// the service and subsequent strings are passed by the process
// that called the StartService function to start the service.
//
// Return value:
// None.
//
VOID WINAPI SvcMain( DWORD dwArgc, LPTSTR *lpszArgv )
{
// Register the handler function for the service
LOGD << "passing 1";
gSvcStatusHandle = RegisterServiceCtrlHandler(
SVCNAME,
SvcCtrlHandler);
LOGD << "passing 2";
if( !gSvcStatusHandle )
{
SvcReportEvent(TEXT("RegisterServiceCtrlHandler"));
return;
}
// These SERVICE_STATUS members remain as set here
LOGD << "passing 3";
gSvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
gSvcStatus.dwServiceSpecificExitCode = 0;
// Report initial status to the SCM
LOGD << "passing 4";
ReportSvcStatus( SERVICE_START_PENDING, NO_ERROR, 3000 );
// Perform service-specific initialization and work.
LOGD << "passing 5";
SvcInit( dwArgc, lpszArgv );
}
我将日志消息放在多行上,但没有得到任何结果。日志文件中没有记录任何内容。
日志消息在服务安装期间有效,但SvcMain函数中没有记录任何内容。
注意::所有内容都经过测试,在作为程序运行时工作正常,包括在Debug中。
1 - 此函数是否执行服务代码? 2 - 是否可以从服务中写入日志文件? 3 - 我还需要在服务中调试哪个其他选项?