Windows service control program

ControlService function (winsvc.h)

Sends a control code to a service.

To specify additional information when stopping a service, use the ControlServiceEx function.

Syntax

Parameters

A handle to the service. This handle is returned by the OpenService or CreateService function. The access rights required for this handle depend on the dwControl code requested.

This parameter can be one of the following control codes.

Control code Meaning
SERVICE_CONTROL_CONTINUE 0x00000003 Notifies a paused service that it should resume. The hService handle must have the SERVICE_PAUSE_CONTINUE access right.
SERVICE_CONTROL_INTERROGATE 0x00000004 Notifies a service that it should report its current status information to the service control manager. The hService handle must have the SERVICE_INTERROGATE access right.

Note that this control is not generally useful as the SCM is aware of the current state of the service.

SERVICE_CONTROL_NETBINDADD 0x00000007 Notifies a network service that there is a new component for binding. The hService handle must have the SERVICE_PAUSE_CONTINUE access right. However, this control code has been deprecated; use Plug and Play functionality instead.
SERVICE_CONTROL_NETBINDDISABLE 0x0000000A Notifies a network service that one of its bindings has been disabled. The hService handle must have the SERVICE_PAUSE_CONTINUE access right. However, this control code has been deprecated; use Plug and Play functionality instead.
SERVICE_CONTROL_NETBINDENABLE 0x00000009 Notifies a network service that a disabled binding has been enabled. The hService handle must have the SERVICE_PAUSE_CONTINUE access right. However, this control code has been deprecated; use Plug and Play functionality instead.
SERVICE_CONTROL_NETBINDREMOVE 0x00000008 Notifies a network service that a component for binding has been removed. The hService handle must have the SERVICE_PAUSE_CONTINUE access right. However, this control code has been deprecated; use Plug and Play functionality instead.
SERVICE_CONTROL_PARAMCHANGE 0x00000006 Notifies a service that its startup parameters have changed. The hService handle must have the SERVICE_PAUSE_CONTINUE access right.
SERVICE_CONTROL_PAUSE 0x00000002 Notifies a service that it should pause. The hService handle must have the SERVICE_PAUSE_CONTINUE access right.
SERVICE_CONTROL_STOP 0x00000001 Notifies a service that it should stop. The hService handle must have the SERVICE_STOP access right.

After sending the stop request to a service, you should not send other controls to the service.

This value can also be a user-defined control code, as described in the following table.

Control code Meaning
Range 128 to 255 The service defines the action associated with the control code. The hService handle must have the SERVICE_USER_DEFINED_CONTROL access right.

A pointer to a SERVICE_STATUS structure that receives the latest service status information. The information returned reflects the most recent status that the service reported to the service control manager.

The service control manager fills in the structure only when GetLastError returns one of the following error codes: NO_ERROR, ERROR_INVALID_SERVICE_CONTROL, ERROR_SERVICE_CANNOT_ACCEPT_CTRL, or ERROR_SERVICE_NOT_ACTIVE. Otherwise, the structure is not filled in.

Return value

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

The following error codes can be set by the service control manager. Other error codes can be set by the registry functions that are called by the service control manager.

Return code Description
ERROR_ACCESS_DENIED The handle does not have the required access right.
ERROR_DEPENDENT_SERVICES_RUNNING The service cannot be stopped because other running services are dependent on it.
ERROR_INVALID_HANDLE The specified handle was not obtained using CreateService or OpenService, or the handle is no longer valid.
ERROR_INVALID_PARAMETER The requested control code is undefined.
ERROR_INVALID_SERVICE_CONTROL The requested control code is not valid, or it is unacceptable to the service.
ERROR_SERVICE_CANNOT_ACCEPT_CTRL The requested control code cannot be sent to the service because the state of the service is SERVICE_STOPPED, SERVICE_START_PENDING, or SERVICE_STOP_PENDING.
ERROR_SERVICE_NOT_ACTIVE The service has not been started.
ERROR_SERVICE_REQUEST_TIMEOUT The process for the service was started, but it did not call StartServiceCtrlDispatcher, or the thread that called StartServiceCtrlDispatcher may be blocked in a control handler function.
ERROR_SHUTDOWN_IN_PROGRESS The system is shutting down.

Remarks

The ControlService function asks the Service Control Manager (SCM) to send the requested control code to the service. The SCM sends the code if the service has specified that it will accept the code, and is in a state in which a control code can be sent to it.

The SCM processes service control notifications in a serial fashion—it will wait for one service to complete processing a service control notification before sending the next one. Because of this, a call to ControlService will block for 30 seconds if any service is busy handling a control code. If the busy service still has not returned from its handler function when the timeout expires, ControlService fails with ERROR_SERVICE_REQUEST_TIMEOUT.

To stop and start a service requires a security descriptor that allows you to do so. The default security descriptor allows the LocalSystem account, and members of the Administrators and Power Users groups to stop and start services. To change the security descriptor of a service, see Modifying the DACL for a Service.

The QueryServiceStatusEx function returns a SERVICE_STATUS_PROCESS structure whose dwCurrentState and dwControlsAccepted members indicate the current state and controls accepted by a running service. All running services accept the SERVICE_CONTROL_INTERROGATE control code by default. Drivers do not accept control codes other than SERVICE_CONTROL_STOP and SERVICE_CONTROL_INTERROGATE. Each service specifies the other control codes that it accepts when it calls the SetServiceStatus function to report its status. A service should always accept these codes when it is running, no matter what it is doing.

The following table shows the action of the SCM in each of the possible service states.

The Complete Service Sample

The topics in this section form a complete service sample:

  • Sample.mc (contains error messages)
  • Svc.cpp (contains the service code)
  • SvcConfig.cpp (contains service configuration code)
  • SvcControl.cpp (contains service control code)

Building the Service

The following procedure describes how to build the service and register the event message DLL.

To build the service and register the event message DLL

Build the message DLL from Sample.mc using the following steps:

  1. mc -U sample.mc
  2. rc -r sample.rc
  3. link -dll -noentry -out:sample.dll sample.res

Build Svc.exe, SvcConfig.exe, and SvcControl.exe from Svc.cpp, SvcConfig.cpp, and SvcControl.cpp, respectively.

Create the registry key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\EventLog\Application\SvcName and add the following registry values to this key.

Value Type Description
EventMessageFile = dll_path REG_SZ The path to the resource-only DLL that contains strings that the service can write to the event log.
TypesSupported = 0x00000007 REG_DWORD A bit mask that specifies the supported event types. The value 0x000000007 indicates that all types are supported.

Testing the Service

The following procedure describes how to test the service.

To test the service

In Control Panel, start the Services application. (In the following steps, use the F5 key to refresh the display after executing a command that modifies the information in the Services application.)

Run the following command to install the service:

svc install

The service writes «Service installed successfully» to the console if the operation succeeds or an error message otherwise.

If the service installation succeeds, the service is displayed in the Services application. Note that Name is set to «SvcName», Description and Status are blank, and Startup Type is set to «Manual».

Run the following command to start the service:

svccontrol start SvcName

If the operation succeeds, the service control program writes «Service start pending. » and then «Service started successfully» to the console. Otherwise, the program writes an error message to the console.

If the service starts successfully, Status is set to «Started». The code in the ServiceMain function is executed by the SCM. If an error occurs, the service will write an error message to the event log. This message includes the name of the function that failed and the error code that was returned on failure.

Run the following command to update the service description:

svcconfig describe SvcName

The service configuration program writes «Service description updated successfully» to the console if the operation succeeds or an error message otherwise.

If the update succeeds, Description is set to «This is a test description».

Run the following command to query the service configuration:

svcconfig query SvcName

The service configuration program writes the service configuration information to the console if the operation succeeds or an error message otherwise.

Run the following command to change the service DACL:

svccontrol dacl SvcName

The service configuration program writes «Service DACL updated successfully» to the console if the operation succeeds or an error message otherwise.

Run the following command to disable the service:

svcconfig disable SvcName

The service configuration program writes «Service disabled successfully» to the console if the operation succeeds or an error message otherwise.

If the service is disabled successfully, Startup Type is set to «Disabled».

Run the following command to enable the service:

svcconfig enable SvcName

The service configuration program writes «Service enabled successfully» to the console if the operation succeeds or an error message otherwise.

If the service is enabled successfully, Startup Type is set to «Manual».

Run the following command to stop the service:

svccontrol stop SvcName

If the operation succeeds, the service control program writes «Service stop pending. » and then «Service stopped successfully» to the console. Otherwise, the program writes an error message to the console.

If the service stops successfully, Status is blank.

If the service fails to stop, the service control program writes an error message to the event log that includes the name of the function that failed and the error code that was returned on failure.

Run the following command to delete the service:

svcconfig delete SvcName

The service configuration program writes «Service deleted successfully» to the console if the operation succeeds or an error message otherwise.

If the service is deleted successfully, it is no longer displayed in the Services application. (Note that if you attempt to delete a service that is not stopped, the operation succeeds but Startup Type is set to «Disabled» and the service entry will be deleted at system restart or when the service is terminated using Task Manager.)

Знакомство с приложениями служб Windows Introduction to Windows Service Applications

Службы Microsoft Windows, ранее известные как службы NT, позволяют создавать долговременные исполняемые приложения, которые запускаются в собственных сеансах Windows. Microsoft Windows services, formerly known as NT services, enable you to create long-running executable applications that run in their own Windows sessions. Для этих служб не предусмотрен пользовательский интерфейс. Они могут запускаться автоматически при загрузке компьютера, их также можно приостанавливать и перезапускать. These services can be automatically started when the computer boots, can be paused and restarted, and do not show any user interface. Благодаря этому службы идеально подходят для использования на сервере, а также в ситуациях, когда необходимы долго выполняемые процессы, которые не мешают работе пользователей на том же компьютере. These features make services ideal for use on a server or whenever you need long-running functionality that does not interfere with other users who are working on the same computer. Службы могут выполняться в контексте безопасности определенной учетной записи пользователя, которая отличается от учетной записи вошедшего в систему пользователя или учетной записи компьютера по умолчанию. You can also run services in the security context of a specific user account that is different from the logged-on user or the default computer account. Дополнительные сведения о службах и сеансах Windows см. в документации по Windows SDK. For more information about services and Windows sessions, see the Windows SDK documentation.

Можно легко создавать службы, создавая приложение, которое устанавливается как служба. You can easily create services by creating an application that is installed as a service. Предположим, что вам нужно отслеживать данные счетчика производительности и реагировать на пороговые значения. For example, suppose you want to monitor performance counter data and react to threshold values. Можно написать и развернуть приложение-службу Windows для прослушивания данных счетчиков, а затем начать сбор и анализ данных. You could write a Windows Service application that listens to the performance counter data, deploy the application, and begin collecting and analyzing data.

Служба будет создана как проект Microsoft Visual Studio с кодом, который определяет, какие команды могут отправляться службе и какие действия должны быть выполнены при получении этих команд. You create your service as a Microsoft Visual Studio project, defining code within it that controls what commands can be sent to the service and what actions should be taken when those commands are received. Команды, которые могут быть отправлены в службу, выполняют запуск, приостановку, возобновление и остановку службы. Также можно выполнять пользовательские команды. Commands that can be sent to a service include starting, pausing, resuming, and stopping the service; you can also execute custom commands.

Созданное приложение можно установить, запустив служебную программу командной строки InstallUtil.exe и передав путь к исполняемому файлу службы. After you create and build the application, you can install it by running the command-line utility InstallUtil.exe and passing the path to the service’s executable file. Затем вы можете использовать диспетчер служб для запуска, остановки, приостановки, продолжения работы и настройки службы. You can then use the Services Control Manager to start, stop, pause, resume, and configure your service. Можно также выполнять многие из этих задач в узле Службы в обозревателе сервера или с помощью класса ServiceController. You can also accomplish many of these same tasks in the Services node in Server Explorer or by using the ServiceController class.

Приложения-службы и другие приложения Visual Studio Service Applications vs. Other Visual Studio Applications

Приложения-службы отличаются от других типов проектов следующим образом: Service applications function differently from many other project types in several ways:

Скомпилированный исполняемый файл, созданный проектом приложения-службы, должен быть установлен на сервере, прежде чем этот проект можно будет использовать надлежащим способом. The compiled executable file that a service application project creates must be installed on the server before the project can function in a meaningful way. Вы не сможете выполнить отладку или запустить приложение службы, нажав клавиши F5 или F11. Вы не сможете сразу же запустить службу или открыть ее код. You cannot debug or run a service application by pressing F5 or F11; you cannot immediately run a service or step into its code. Вместо этого необходимо установить и запустить службу, а затем подключить отладчик к процессу службы. Instead, you must install and start your service, and then attach a debugger to the service’s process. Дополнительные сведения см. в разделе Практическое руководство. Отладка приложений служб Windows. For more information, see How to: Debug Windows Service Applications.

В отличие от некоторых типов проектов для приложений-служб необходимо создавать компоненты установки. Unlike some types of projects, you must create installation components for service applications. Компоненты установки устанавливают и регистрируют службу на сервере и создают для нее запись с помощью диспетчера служб Windows. The installation components install and register the service on the server and create an entry for your service with the Windows Services Control Manager. Дополнительные сведения см. в разделе Практическое руководство. Добавление установщиков в приложение-службу. For more information, see How to: Add Installers to Your Service Application.

Метод Main для приложения службы должен выдать команду запуска для служб, которые содержит проект. The Main method for your service application must issue the Run command for the services your project contains. Метод Run загружает службы в диспетчер служб на соответствующем сервере. The Run method loads the services into the Services Control Manager on the appropriate server. Если вы используете шаблон проекта служб Windows, этот метод создается автоматически. If you use the Windows Services project template, this method is written for you automatically. Обратите внимание, что загрузка службы — не то же самое, что ее запуск. Note that loading a service is not the same thing as starting the service. Дополнительные сведения см. в разделе «Время существования службы». See «Service Lifetime» below for more information.

Приложения-службы Windows выполняются в отдельной оконной станции, отличной от интерактивной станции вошедшего пользователя. Windows Service applications run in a different window station than the interactive station of the logged-on user. Оконная станция — это безопасный объект, который содержит буфер обмена, набор глобальных атомов и группу объектов рабочего стола. A window station is a secure object that contains a Clipboard, a set of global atoms, and a group of desktop objects. Так как станция службы Windows не является интерактивной, диалоговые окна, отображаемые в приложении-службе Windows, не будут видны, что может привести к зависанию программы. Because the station of the Windows service is not an interactive station, dialog boxes raised from within a Windows service application will not be seen and may cause your program to stop responding. Точно так же сообщения об ошибках должны записываться в журнал событий Windows, а не появляться в пользовательском интерфейсе. Similarly, error messages should be logged in the Windows event log rather than raised in the user interface.

Классы службы Windows, поддерживаемые платформой .NET Framework, не поддерживают взаимодействие с интерактивными станциями, т. е. станциями вошедшего в систему пользователя. The Windows service classes supported by the .NET Framework do not support interaction with interactive stations, that is, the logged-on user. Платформа .NET Framework также не включает классы, которые представляют станции и рабочие столы. The .NET Framework also does not include classes that represent stations and desktops. Если служба Windows должна взаимодействовать с другими станциями, нужно получить доступ к неуправляемому API Windows. If your Windows service must interact with other stations, you will need to access the unmanaged Windows API. Дополнительные сведения см. в документации по Windows SDK. For more information, see the Windows SDK documentation.

Взаимодействие службы Windows с пользователем или другими станциями необходимо тщательно спроектировать, чтобы включить такие сценарии, когда вошедшего пользователя нет или у пользователя есть непредвиденный набор объектов рабочего стола. The interaction of the Windows service with the user or other stations must be carefully designed to include scenarios such as there being no logged on user, or the user having an unexpected set of desktop objects. В некоторых случаях удобнее создать приложение Windows, которое будет выполняться под управлением пользователя. In some cases, it may be more appropriate to write a Windows application that runs under the control of the user.

Приложения-службы Windows выполняются в собственном контексте безопасности. Они запускаются, прежде чем пользователь войдет на компьютер Windows, на котором они установлены. Windows service applications run in their own security context and are started before the user logs into the Windows computer on which they are installed. Следует тщательно планировать, в какой учетной записи пользователя будет выполняться служба. Если это системная учетная запись, у службы будет больше разрешений и прав на доступ, чем при использовании учетной записи пользователя. You should plan carefully what user account to run the service within; a service running under the system account has more permissions and privileges than a user account.

Время существования службы Service Lifetime

Служба проходит через несколько внутренних состояний за время своего существования. A service goes through several internal states in its lifetime. Во-первых, служба устанавливается в системе, в которой она будет выполняться. First, the service is installed onto the system on which it will run. Этот процесс выполняет установщики для проекта службы и загружает службу в диспетчер служб для этого компьютера. This process executes the installers for the service project and loads the service into the Services Control Manager for that computer. Диспетчер служб — это основное средство управления службами в Windows. The Services Control Manager is the central utility provided by Windows to administer services.

Загруженную службу необходимо запустить. After the service has been loaded, it must be started. Запущенная служба может выполнять свои задачи. Starting the service allows it to begin functioning. Запустите службу из диспетчера служб или обозревателя сервера либо из кода, вызвав метод Start. You can start a service from the Services Control Manager, from Server Explorer, or from code by calling the Start method. Метод Start передает обработку в метод OnStart приложения и обрабатывает любой код, определенный там. The Start method passes processing to the application’s OnStart method and processes any code you have defined there.

Запущенная служба может находиться в этом состоянии бесконечно, пока она не будет остановлена или приостановлена либо работа компьютера не будет завершена. A running service can exist in this state indefinitely until it is either stopped or paused or until the computer shuts down. Есть три основных состояния службы: Running, Paused и Stopped. A service can exist in one of three basic states: Running, Paused, or Stopped. Служба также может сообщать состояние ожидания выполнения команды: ContinuePending, PausePending, StartPending или StopPending. The service can also report the state of a pending command: ContinuePending, PausePending, StartPending, or StopPending. Эти состояния указывают, что команда выдана (например, команда для приостановки службы или запуска службы), но еще не выполнена. These statuses indicate that a command has been issued, such as a command to pause a running service, but has not been carried out yet. Вы можете запросить свойство Status, чтобы определить, в каком состоянии находится служба, или использовать WaitForStatus, чтобы выполнить действие при наступлении любого из этих состояний. You can query the Status to determine what state a service is in, or use the WaitForStatus to carry out an action when any of these states occurs.

Вы можете приостановить, остановить или возобновить работу службы из диспетчера служб или обозревателя сервера либо из кода, вызвав методы. You can pause, stop, or resume a service from the Services Control Manager, from Server Explorer, or by calling methods in code. Каждое из этих действий вызывает соответствующую процедуру в службе (OnStop, OnPause или OnContinue), в которой можно определить дополнительную обработку на случай изменения состояния службы. Each of these actions can call an associated procedure in the service (OnStop, OnPause, or OnContinue), in which you can define additional processing to be performed when the service changes state.

Типы служб Types of Services

Есть два типа служб, которые можно создать в Visual Studio с помощью .NET Framework. There are two types of services you can create in Visual Studio using the .NET Framework. Службам, которые являются единственными службами в процессе, назначается тип Win32OwnProcess. Services that are the only service in a process are assigned the type Win32OwnProcess. Службам, которые включены в процесс вместе с другими службами, назначается тип Win32ShareProcess. Services that share a process with another service are assigned the type Win32ShareProcess. Тип службы можно получить, запросив свойство ServiceType. You can retrieve the service type by querying the ServiceType property.

Вы можете время от времени встречать другие типы служб при выполнении запроса к службам, которые не были созданы в Visual Studio. You might occasionally see other service types if you query existing services that were not created in Visual Studio. Дополнительные сведения см. здесь: ServiceType. For more information on these, see the ServiceType.

Службы и компонент ServiceController Services and the ServiceController Component

Компонент ServiceController используется для подключения к установленной службе и изменения ее состояния. С помощью компонента ServiceController вы можете запускать, останавливать, приостанавливать и продолжать работу службы, а также отправлять службе пользовательские команды. The ServiceController component is used to connect to an installed service and manipulate its state; using a ServiceController component, you can start and stop a service, pause and continue its functioning, and send custom commands to a service. Использовать компонент ServiceController при создании приложения-службы не нужно. However, you do not need to use a ServiceController component when you create a service application. Фактически, в большинстве случаев компонент ServiceController должен находиться в приложении, отдельном от приложения-службы Windows, которое определяет службу. In fact, in most cases your ServiceController component should exist in a separate application from the Windows service application that defines your service.

Для получения дополнительной информации см. ServiceController. For more information, see ServiceController.

Требования Requirements

Службы должны создаваться в проекте приложения-службы Windows или другом проекте с поддержкой .NET Framework, который создает исполняемый файл при сборке и наследуется от класса ServiceBase. Services must be created in a Windows Service application project or another .NET Framework–enabled project that creates an .exe file when built and inherits from the ServiceBase class.

Проекты, которые содержат службы Windows, должны включать компоненты установки для проекта и его служб. Projects containing Windows services must have installation components for the project and its services. Это легко сделать с помощью окна свойств. This can be easily accomplished from the Properties window. Дополнительные сведения см. в разделе Практическое руководство. Добавление установщиков в приложение-службу. For more information, see How to: Add Installers to Your Service Application.

Читайте также:  Активатор windows 10 pro x64 софтпортал
Оцените статью