Windows service start dword

Using the registry editor to change the service state

[HKEY_LOCAL_MACHINE \System \CurrentControlSet \Services]

Within the Services-key find go to the short-name of the wanted service (Here RpcSS aka. Remote Procedure Call (RPC)):

[HKEY_LOCAL_MACHINE \System \CurrentControlSet \Services \RpcSS]

Double-Click the Start-value in the list to the right.

  • Change Value data: to the wanted state:
    • 0 = Boot
    • 1 = System
    • 2 = Automatic
    • 3 = Manual
    • 4 = Disabled
  • Press Ok and exit the Registry Editor.
  • If setting a service to Disabled or Manual, then execute this command to stop the service:

    Note in this guide the short-name of a service is shown just in parenthesis next to the «Process Name».

    Note the «Automatic» startup mode was extended with «Automatic (Delayed Start)» with Windows Vista/2008. It specifies that the service startup can be delayed until after having performed user logon. It can be activated with the following DWORD registry setting:

    [HKEY_LOCAL_MACHINE \System \CurrentControlSet \Services \BITS]
    DelayedAutoStart = 1
    Start = 2

    ГЛАВА 13

    Серверные программы, рассмотренные в главах 11 и 12, являются консольными приложениями, выполняющимися как фоновые задачи. Вообще говоря, эти серверы могут выполняться в течение неопределенно длительного времени, обслуживая многочисленных клиентов по мере того, как те будут подключаться к серверу, посылать запросы, принимать ответы и разрывать соединения. Таким образом, указанные серверы могут работать как службы непрерывного действия, однако, чтобы быть в полной мере эффективными, эти службы должны быть управляемыми.

    Службы Windows Services,[33] известные ранее под названием NT Services, предоставляют все средства управления, необходимые для превращения наших серверов в службы, которые могут активизироваться по команде или во время запуска системы еще до входа в нее пользователей, приостанавливаться, а также возобновлять или прекращать свое выполнение. Службы могут даже осуществлять мониторинг работоспособности самих служб. Информация о службах хранится в системном реестре.

    В конечном счете, любая серверная система наподобие тех, которые были разработаны в главах 11 и 12, должна быть преобразована в службу, особенно в тех случаях, когда она предназначена для использования широким кругом клиентов или внутри организации.

    Windows предоставляет целый ряд служб; в качестве примера можно привести службы telnet, отправки и приема факсимильных сообщений, а также службы управления безопасностью учетных записей и драйверы устройств. Доступ ко всем службам можно получить через пиктограмму Administrative Tools (Администрирование), который находится в окне панели управления.

    Примитивную форму управления сервером можно было наблюдать в приведенной в главе 6 программе JobShell (программа 6.3), которая обеспечивает возможность перевода сервера под управление задачи и его остановку путем посылки сигнала завершения работы. В то же время, службы Windows Services предоставляют гораздо более широкие возможности и отличаются высокой надежностью, как это будет продемонстрировано в данной главе на примере преобразования программы к форме, обеспечивающей управление службами Windows Services.

    В данной главе также показано, как преобразовать существующее консольное приложение в службу Windows, осуществить ее установку, а также организовать мониторинг и управление этой службой. Кроме того, здесь рассматривается ведение журнала учета событий, что обеспечивает регистрацию действий службы.

    Читайте также:  Как соединить два тома жесткого диска windows 10

    Написание программ, реализующихслужбы Windows Services: обзор

    Службы Windows выполняются под управлением диспетчера управления службами (Service Control Manager, SCM). Преобразование консольного приложения, такого как serverNP или serverSK, в службу Windows осуществляется в три этапа, после выполнения которых программа переходит под управление SCM.

    1. Создание новой точки входа main(), которая регистрирует службу в SCM, предоставляя точки входа и имена логических служб.

    2. Преобразование прежней функции точки входа main() в функцию ServiceMain(), которая регистрирует обработчик управляющих команд службы и информирует SCM о своем состоянии. Остальная часть кода, по существу, сохраняет прежний вид, хотя и может быть дополнена командами регистрации событий. Имя ServiceMain() является заменителем имени логической службы, причем логических служб может быть несколько.

    3. Написание функции обработчика управляющих команд службы, которая должна предпринимать определенные действия в ответ на команды, поступающие от SCM.

    По мере описания каждого из этих трех этапов будут даваться отдельные разъяснения, касающиеся создания служб, их запуска и управления ими. Более подробные сведения приводятся в последующих разделах, а взаимодействие между отдельными компонентами службы иллюстрируется на рис. 13.1 далее в этой главе.

    Функция main()

    Задачей новой функции main(), которая вызывается SCM, является регистрация службы в SCM и запуск диспетчера службы (service control dispatcher). Для этого необходимо вызвать функцию StartServiceControlDispatcher, передав ей имя (имена) и точку (точки) входа одной или нескольких логических служб.

    BOOL StartServiceCtrlDispatcher(LPSERVICE_TABLE_ENTRY lpServiceStartTable)

    Эта функция принимает единственный аргумент lpServiceStartTable, являющийся адресом массива элементов SERVICE_TABLE_ENTRY, каждый из которых представляет имя и точку входа логической службы. Конец массива обозначается двумя последовательными значениями NULL.

    Функция возвращает значение TRUE, если регистрация службы прошла успешно. Если служба уже выполняется или возникают проблемы с обновлением записей реестра (HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services), функция завершается с ошибками, обработка которых может осуществляться обычным путем.

    Основной поток процесса службы, которая вызывает функцию StartService-ControlDispatcher, связывает поток с SCM. SCM регистрирует службу с вызывающим потоком в качестве потока диспетчера службы. SCM не осуществляет возврата в вызывающий поток до тех пор, пока не завершат выполнение все службы. Заметьте, однако, что фактического запуска логических служб в этот момент не происходит; запуск службы требует вызова функции StartService, которая описывается далее в этой главе.

    Типичная основная программа службы, соответствующая случаю единственной логической службы, представлена в программе 13.1.

    Программа 13.1. main: точка входа main службы

    void WINAPI ServiceMain(DWORD argc, LPTSTR argv[]);

    static LPTSTR ServiceName = _T(«SocketCommandLineService»);

    /* Главная программа запуска диспетчера службы. */

    SERVICE_STATUS structure (winsvc.h)

    Contains status information for a service. The ControlService, EnumDependentServices, EnumServicesStatus, and QueryServiceStatus functions use this structure. A service uses this structure in the SetServiceStatus function to report its current status to the service control manager.

    Syntax

    Members

    The type of service. This member can be one of the following values.

    Value Meaning
    SERVICE_FILE_SYSTEM_DRIVER 0x00000002 The service is a file system driver.
    SERVICE_KERNEL_DRIVER 0x00000001 The service is a device driver.
    SERVICE_WIN32_OWN_PROCESS 0x00000010 The service runs in its own process.
    SERVICE_WIN32_SHARE_PROCESS 0x00000020 The service shares a process with other services.
    SERVICE_USER_OWN_PROCESS 0x00000050 The service runs in its own process under the logged-on user account.
    SERVICE_USER_SHARE_PROCESS 0x00000060 The service shares a process with one or more other services that run under the logged-on user account.
    Читайте также:  Не сохраняются настройки общего доступа windows server 2016

    В

    If the service type is either SERVICE_WIN32_OWN_PROCESS or SERVICE_WIN32_SHARE_PROCESS, and the service is running in the context of the LocalSystem account, the following type may also be specified.

    Value Meaning
    SERVICE_INTERACTIVE_PROCESS 0x00000100 The service can interact with the desktop.

    The current state of the service. This member can be one of the following values.

    Value Meaning
    SERVICE_CONTINUE_PENDING 0x00000005 The service continue is pending.
    SERVICE_PAUSE_PENDING 0x00000006 The service pause is pending.
    SERVICE_PAUSED 0x00000007 The service is paused.
    SERVICE_RUNNING 0x00000004 The service is running.
    SERVICE_START_PENDING 0x00000002 The service is starting.
    SERVICE_STOP_PENDING 0x00000003 The service is stopping.
    SERVICE_STOPPED 0x00000001 The service is not running.

    The control codes the service accepts and processes in its handler function (see Handler and HandlerEx). A user interface process can control a service by specifying a control command in the ControlService or ControlServiceEx function. By default, all services accept the SERVICE_CONTROL_INTERROGATE value.

    To accept the SERVICE_CONTROL_DEVICEEVENT value, the service must register to receive device events by using the RegisterDeviceNotification function.

    The following are the control codes.

    Control code Meaning
    SERVICE_ACCEPT_NETBINDCHANGE 0x00000010 The service is a network component that can accept changes in its binding without being stopped and restarted.

    This control code allows the service to receive SERVICE_CONTROL_NETBINDADD, SERVICE_CONTROL_NETBINDREMOVE, SERVICE_CONTROL_NETBINDENABLE, and SERVICE_CONTROL_NETBINDDISABLE notifications.

    SERVICE_ACCEPT_PARAMCHANGE 0x00000008 The service can reread its startup parameters without being stopped and restarted.

    This control code allows the service to receive SERVICE_CONTROL_PARAMCHANGE notifications.

    SERVICE_ACCEPT_PAUSE_CONTINUE 0x00000002 The service can be paused and continued.

    This control code allows the service to receive SERVICE_CONTROL_PAUSE and SERVICE_CONTROL_CONTINUE notifications.

    SERVICE_ACCEPT_PRESHUTDOWN 0x00000100 The service can perform preshutdown tasks.

    This control code enables the service to receive SERVICE_CONTROL_PRESHUTDOWN notifications. Note that ControlService and ControlServiceEx cannot send this notification; only the system can send it.

    Windows ServerВ 2003 and WindowsВ XP:В В This value is not supported.

    SERVICE_ACCEPT_SHUTDOWN 0x00000004 The service is notified when system shutdown occurs.

    This control code allows the service to receive SERVICE_CONTROL_SHUTDOWN notifications. Note that ControlService and ControlServiceEx cannot send this notification; only the system can send it.

    SERVICE_ACCEPT_STOP 0x00000001 The service can be stopped.

    This control code allows the service to receive SERVICE_CONTROL_STOP notifications.

    This member can also contain the following extended control codes, which are supported only by HandlerEx. (Note that these control codes cannot be sent by ControlService or ControlServiceEx.)

    Control code Meaning
    SERVICE_ACCEPT_HARDWAREPROFILECHANGE 0x00000020 The service is notified when the computer’s hardware profile has changed. This enables the system to send SERVICE_CONTROL_HARDWAREPROFILECHANGE notifications to the service.
    SERVICE_ACCEPT_POWEREVENT 0x00000040 The service is notified when the computer’s power status has changed. This enables the system to send SERVICE_CONTROL_POWEREVENT notifications to the service.
    SERVICE_ACCEPT_SESSIONCHANGE 0x00000080 The service is notified when the computer’s session status has changed. This enables the system to send SERVICE_CONTROL_SESSIONCHANGE notifications to the service.
    SERVICE_ACCEPT_TIMECHANGE 0x00000200 The service is notified when the system time has changed. This enables the system to send SERVICE_CONTROL_TIMECHANGE notifications to the service.

    Windows ServerВ 2008, WindowsВ Vista, Windows ServerВ 2003 and WindowsВ XP:В В This control code is not supported.

    SERVICE_ACCEPT_TRIGGEREVENT 0x00000400 The service is notified when an event for which the service has registered occurs. This enables the system to send SERVICE_CONTROL_TRIGGEREVENT notifications to the service.

    Windows ServerВ 2008, WindowsВ Vista, Windows ServerВ 2003 and WindowsВ XP:В В This control code is not supported.

    SERVICE_ACCEPT_USERMODEREBOOT 0x00000800 The services is notified when the user initiates a reboot.

    Windows ServerВ 2008В R2, WindowsВ 7, Windows ServerВ 2008, WindowsВ Vista, Windows ServerВ 2003 and WindowsВ XP:В В This control code is not supported.

    The error code the service uses to report an error that occurs when it is starting or stopping. To return an error code specific to the service, the service must set this value to ERROR_SERVICE_SPECIFIC_ERROR to indicate that the dwServiceSpecificExitCode member contains the error code. The service should set this value to NO_ERROR when it is running and on normal termination.

    A service-specific error code that the service returns when an error occurs while the service is starting or stopping. This value is ignored unless the dwWin32ExitCode member is set to ERROR_SERVICE_SPECIFIC_ERROR.

    The check-point value the service increments periodically to report its progress during a lengthy start, stop, pause, or continue operation. For example, the service should increment this value as it completes each step of its initialization when it is starting up. The user interface program that invoked the operation on the service uses this value to track the progress of the service during a lengthy operation. This value is not valid and should be zero when the service does not have a start, stop, pause, or continue operation pending.

    The estimated time required for a pending start, stop, pause, or continue operation, in milliseconds. Before the specified amount of time has elapsed, the service should make its next call to the SetServiceStatus function with either an incremented dwCheckPoint value or a change in dwCurrentState. If the amount of time specified by dwWaitHint passes, and dwCheckPoint has not been incremented or dwCurrentState has not changed, the service control manager or service control program can assume that an error has occurred and the service should be stopped. However, if the service shares a process with other services, the service control manager cannot terminate the service application because it would have to terminate the other services sharing the process as well.

    Читайте также:  Укажите элементы рабочего стола windows
    Оцените статью