HOME> 家族联盟> 编写服务程序主函数 - Win32 apps
{$vo.文章标题}
{$vo.文章标题}

编写服务程序主函数 - Win32 apps

admin
9363

服务程序的main 函数调用 StartServiceCtrlDispatcher 函数以连接到服务控制管理器 (SCM) 并启动控制调度程序线程。 调度程序线程循环,等待调度表中指定服务的传入控制请求。 当出现错误或进程中的所有服务已终止时,此线程将返回 。 当进程中的所有服务都终止时,SCM 会向调度程序线程发送控制请求,告知其退出。 然后,此线程从 StartServiceCtrlDispatcher 调用返回,进程可以终止。

此示例使用以下全局定义。

#define SVCNAME TEXT("SvcName")

SERVICE_STATUS gSvcStatus;

SERVICE_STATUS_HANDLE gSvcStatusHandle;

HANDLE ghSvcStopEvent = NULL;

以下示例可用作支持单个服务的服务程序的入口点。 如果服务程序支持多个服务,请将其他服务的名称添加到调度表,以便调度程序线程可以监视这些服务。

_tmain函数是入口点。 SvcReportEvent 函数将信息性消息和错误写入事件日志。 有关编写 SvcMain 函数的信息,请参阅 编写 ServiceMain 函数。 有关 SvcInstall 函数的详细信息,请参阅 安装服务。 有关编写 SvcCtrlHandler 函数的信息,请参阅 编写控件处理程序函数。 有关完整的示例服务(包括 SvcReportEvent 函数的源),请参阅 Svc.cpp。

//

// Purpose:

// Entry point for the process

//

// Parameters:

// None

//

// Return value:

// None, defaults to 0 (zero)

//

int __cdecl _tmain(int argc, TCHAR *argv[])

{

// If command-line parameter is "install", install the service.

// Otherwise, the service is probably being started by the SCM.

if( lstrcmpi( argv[1], TEXT("install")) == 0 )

{

SvcInstall();

return;

}

// 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"));

}

}

下面是消息编译器生成的示例 Sample.h。 有关详细信息,请参阅 Sample.mc。

// The following are message definitions.

//

// Values are 32 bit values layed out as follows:

//

// 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1

// 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0

// +---+-+-+-----------------------+-------------------------------+

// |Sev|C|R| Facility | Code |

// +---+-+-+-----------------------+-------------------------------+

//

// where

//

// Sev - is the severity code

//

// 00 - Success

// 01 - Informational

// 10 - Warning

// 11 - Error

//

// C - is the Customer code flag

//

// R - is a reserved bit

//

// Facility - is the facility code

//

// Code - is the facility's status code

//

//

// Define the facility codes

//

#define FACILITY_SYSTEM 0x0

#define FACILITY_STUBS 0x3

#define FACILITY_RUNTIME 0x2

#define FACILITY_IO_ERROR_CODE 0x4

//

// Define the severity codes

//

#define STATUS_SEVERITY_WARNING 0x2

#define STATUS_SEVERITY_SUCCESS 0x0

#define STATUS_SEVERITY_INFORMATIONAL 0x1

#define STATUS_SEVERITY_ERROR 0x3

//

// MessageId: SVC_ERROR

//

// MessageText:

//

// An error has occurred (%2).

//

//

#define SVC_ERROR ((DWORD)0xC0020001L)

相关主题

服务入口点

完整服务示例