Share via


Escribir la función principal de un programa de servicio

La función principal de un programa de servicio llama a la función StartServiceCtrlDispatcher para conectarse al administrador de control de servicios (SCM) e iniciar el subproceso del distribuidor de controles. El subproceso del distribuidor se repite, esperando solicitudes de control entrantes para los servicios especificados en la tabla de distribución. Este subproceso devuelve cuando se produce un error o cuando todos los servicios del proceso han finalizado. Cuando todos los servicios del proceso han finalizado, el SCM envía una solicitud de control al subproceso del distribuidor que le indica que salga. A continuación, este subproceso devuelve desde la llamada StartServiceCtrlDispatcher y el proceso puede finalizar.

En este ejemplo se usan las siguientes definiciones globales.

#define SVCNAME TEXT("SvcName")

SERVICE_STATUS          gSvcStatus; 
SERVICE_STATUS_HANDLE   gSvcStatusHandle; 
HANDLE                  ghSvcStopEvent = NULL;

En el ejemplo siguiente se puede usar como punto de entrada para un programa de servicio que admita un único servicio. Si el programa de servicio admite varios servicios, agregue los nombres de los servicios adicionales a la tabla de distribución para que el subproceso del distribuidor pueda supervisarlos.

La función _tmain es el punto de entrada. La función SvcReportEvent escribe mensajes informativos y errores en el registro de eventos. Para obtener información sobre cómo escribir la función SvcMain, consulte Escritura de una función ServiceMain. Para obtener más información sobre la función SvcInstall, consulte Instalación de un servicio. Para obtener información sobre cómo escribir la función SvcCtrlHandler, vea Escribir una función de controlador de control. Para obtener el servicio de ejemplo completo, incluido el origen de la función SvcReportEvent, consulte 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")); 
    } 
} 

A continuación se muestra un ejemplo sample.h generado por el compilador de mensajes. Para obtener más información, consulte 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)

Punto de entrada de servicio

Ejemplo de servicio completo