Windows service automatic start

Start or stop Windows service from command line (CMD)

We normally use Services.msc to start or stop or disable or enable any service. We can do the same from windows command line also using net and sc utilities. Below are commands for controlling the operation of a service.

Command to stop a service:

To start a service:

You need to have administrator privileges to run net start/stop commands. If you are just a normal user on the computer, you would get an error like below.

To disable a service:

To enable a service:

To make a service start automatically with system boot:

Note: Space is mandatory after ‘=’ in the above sc commands.

This SC command works on a Windows 7 machine and also on the down-level editions of Windows i.e Windows XP/2003 and Windows Vista. Again, if you do not have administrator previliges you would get the below error.

Note that the service name is not the display name of a service. Each service is given a unique identification name which can be used with net or sc commands. For example, Remote procedure call (RPC) is the display name of the service. But the service name we need to use in the above commands is RpcSs.
So to start Remote procedure call service the command is:

These service names are listed below for each service. The first column shows the display name of a service and the second column shows the service name that should be used in net start or net stop or sc config commands.

Automatically Starting Services

During system boot, the SCM starts all auto-start services and the services on which they depend. For example, if an auto-start service depends on a demand-start service, the demand-start service is also started automatically.

The load order is determined by the following:

The order of groups in the load ordering group list. This information is stored in the ServiceGroupOrder value in the following registry key:

HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control

To specify the load ordering group for a service, use the lpLoadOrderGroup parameter of the CreateService or ChangeServiceConfig function.

The order of services within a group specified in the tags order vector. This information is stored in the GroupOrderList value in the following registry key:

HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control

The dependencies listed for each service.

When the boot is complete, the system executes the boot verification program specified by the BootVerificationProgram value of the following registry key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control.

By default, this value is not set. The system simply reports that the boot was successful after the first user has logged on. You can supply a boot verification program that checks the system for problems and reports the boot status to the SCM using the NotifyBootConfigStatus function.

After a successful boot, the system saves a clone of the database in the last-known-good (LKG) configuration. The system can restore this copy of the database if changes made to the active database cause the system reboot to fail. The following is the registry key for this database:

HKEY_LOCAL_MACHINE\SYSTEM\ControlSetXXX\Services

where XXX is the value saved in the following registry value: HKEY_LOCAL_MACHINE\System\Select\LastKnownGood.

Читайте также:  Обновление времени mac os

If an auto-start service with a SERVICE_ERROR_CRITICAL error control level fails to start, the SCM reboots the computer using the LKG configuration. If the LKG configuration is already being used, the boot fails.

An auto-start service can be configured as a delayed auto-start service by calling the ChangeServiceConfig2 function with SERVICE_CONFIG_DELAYED_AUTO_START_INFO. This change takes effect after the next system boot. For more information, see SERVICE_DELAYED_AUTO_START_INFO.

Функция отложенного запуска: новые возможности для служб Windows

Любому администратору хоть раз приходилось добавлять в автозагрузку сервера задачи, требующие выполнения в строго определенной последовательности. У меня чаще всего возникают проблемы со службами, для нормальной работы которых необходимо подключение к базе данных на этом же сервере. Раньше это решалось с помощью изощренных сценариев или путем запуска приложений вне служебной среды Windows (страшно вспомнить), но в новых продуктах Windows предусмотрена специальная опция, позволяющая управлять автоматической загрузкой.

В Windows Server 2008, Windows Vista и Windows 7 появилась новая опция запуска служб: «Автоматически (отложенный запуск)» (Automatic (Delayed Start)). Она позволяет решить описанную выше проблему с запуском приложения, которое требует подключения к базе данных на этом же сервере для корректного функционирования. Для сервера базы данных в таком случае следует выбрать традиционный режим автоматического запуска, а для приложения — режим отложенного запуска.

Опция отложенного запуска позволяет оптимизировать процесс загрузки системы и облегчает настройку приложений для последовательной автозагрузки. Процесс настройки отложенного запуска для служб ничем не отличается от традиционного (рис. A).

Настроить отложенный запуск можно не только посредством графического интерфейса, но и в реестре, изменив значение параметра Dword в разделе «DelayedAutoStart». При этом все стандартные службы, работающие в автоматическом режиме, запущены не будут: службам, для которых выбран отложенный запуск, просто будет присвоен пониженный приоритет.

Процесс настройки отложенного запуска для служб Windows описывается в блоге TechNet.

В предыдущих версиях Windows при загрузке системы процесс диспетчера сеансов (Session Manager, SMSS.EXE) запускал клиент-серверную подсистему (Client-Server Runtime Subsystem, CSRSS.EXE) и процесс входа в систему (WINLOGON.EXE). Последний запускал процесс сервера проверки подлинности локальной системы безопасности (Local Security Authority Subsystem Service, LSASS.EXE) и диспетчер управления службами (Service Control Manager, SERVICES.EXE). При консольном входе пользователь подключался к сеансу 0 (Session 0), который использовался и системными процессами. Недостаток такого подхода заключался в том, что при наличии у некорректно составленной службы Windows, запущенной в сеансе 0, пользовательского интерфейса в интерактивной консоли, вредоносное программное обеспечение могло атаковать данное окно с использованием сообщений и получить административные права.

Чтобы решить эту проблему, некоторые системные процессы в Windows Vista и Windows Server 2008 были усовершенствованы. SMSS.EXE, как и в предыдущих версиях, по-прежнему является первым пользовательским процессом, запускаемым при загрузке системы. Однако теперь он запускается в двух экземплярах, один из которых отвечает за настройку сеанса 0 для системных процессов. Экземпляр SMSS.EXE, отвечающий за сеанс 0, запускает приложение инициализации Windows (Windows Startup Application, WININIT.EXE) и экземпляр CSRSS.EXE для сеанса 0, а затем завершается. WININIT.EXE продолжает загрузку, запуская SERVICES.EXE и LSASS.EXE, а также новый процесс — диспетчер локальных сеансов (Local Session Manager, LSM.EXE), управляющий подключениями терминального сервера на данном компьютере.

Одновременно с сеансом 0 инициализируется сеанс консоли (Console session). Первый экземпляр SMSS.EXE создает новую копию самого себя для настройки сеанса консоли, как и в случае с сеансом 0. Новый экземпляр SMSS.EXE запускает CSRSS.EXE и WINLOGON.EXE для сеанса консоли, готовя систему к входу пользователя. После этого WINLOGON.EXE запускает хост-интерфейс входа пользователя (Logon User Interface Host, LOGONUI.EXE), который, в свою очередь, выводит окно «Параметры безопасности» (Windows Security) с предложением нажать [Ctrl]+[Alt]+[Delete] для входа.

Читайте также:  Рабочий стол перевернулся вверх ногами как вернуть обратно windows

Здесь стоит сказать несколько слов о процессе Winlogon. В прошлых версиях Windows процесс WINLOGON.EXE запускал библиотеку DLL графической идентификации и проверки подлинности (Graphical Identification and Authentication, GINA), указанную в реестре, для вывода интерфейса входа в систему с предложением ввести данные учетной записи пользователя. В Windows Vista и Windows Server 2008 библиотека GINA не используется — вместо нее реализована новая архитектура поставщиков учетных данных (Credential Provider). WINLOGON.EXE запускает LOGONUI.EXE для загрузки поставщиков учетных данных, которые настраиваются в разделе реестра «HKLM\Software\Microsoft\Windows NT\CurrentVersion\Authentication\Credential Providers». LogonUI управляет пользовательским интерфейсом и может последовательно запускать несколько поставщиков учетных данных. Поставщики учетных данных могут использоваться для вывода на экран входа в систему определенных элементов. LOGONUI.EXE передает данные учетной записи пользователя процессу WINLOGON.EXE и завершается.

При попытке входа в систему первый экземпляр SMSS.EXE создает новую копию самого себя для настройки нового сеанса, как в случае с сеансом 0 и сеансом консоли. Новый экземпляр SMSS.EXE запускает процессы CSRSS.EXE и WINLOGON.EXE для нового сеанса. WINLOGON.EXE запускает LOGONUI.EXE для вывода экрана входа в систему. На первый взгляд может показаться, что такой механизм создает излишнюю нагрузку на систему. На клиентских компьютерах особой пользы от этого действительно нет. Но в случае с терминальными серверами Windows Server 2008, возможность одновременного выполнения нескольких экземпляров SMSS.EXE ускоряет процесс входа в систему для нескольких пользователей одновременно.

Теперь расскажем вкратце о другой новой функции Windows Vista и Windows Server 2008 — отложенном запуске системных служб. Данная опция позволяет решить проблему автоматического запуска большого числа служб, создающих серьезную нагрузку при старте системы. Теперь те службы, запуск которых в самом начале процесса загрузки системы необязателен, стартуют в отложенном режиме, что существенно ускоряет процесс. Службы, для которых выбрана данная опция, запускаются вскоре после загрузки системы.

Как же действует новая функция? Диспетчер управления службами запускает службы, для которых выбран отложенный запуск, после загрузки цепочки процессов, отмеченных для автозапуска. Цепочке служб, запускаемых в отложенном режиме, присваивается приоритет THREAD_PRIORITY_LOWEST, и соответственно, все операции ввода/вывода, инициируемые данными службами, имеют самый низкий приоритет. После инициализации службы диспетчер управления службами вновь присваивает ей нормальный приоритет.

Сочетание отложенного запуска, пониженного приоритета для ЦП, оперативной памяти и фоновых операций ввода/вывода, значительно снижает нагрузку на систему, не препятствуя нормальному входу пользователя. Многие службы Windows, включая фоновую интеллектуальную службу передачи (Background Intelligent Transfer Service, BITS), клиент Центра обновления Windows (Windows Update Client) и службу Windows Media Center, теперь запускаются в отложенном режиме, чтобы ускорить процесс входа в систему при загрузке. Чтобы настроить службу для автоматического запуска в отложенном режиме, следует создать параметр REG_DWORD с именем «DelayedAutoStart» в подразделе конфигурации для данной службы в разделе «HKLM\SYSTEM\CurrentControlSet\Services».

Automatic vs Automatic (Delayed start) Service Startup types

The Services console ( services.msc ) in Windows lets you configure the startup type of Windows Services. As you know, you can choose one of the options from the dropdown: Automatic (Delayed Start), Automatic, Manual, or Disabled.

But, do you know what’s the difference between Automatic and Automatic (Delayed Start).

Automatic vs Automatic (Delayed start) Startup types

If a service startup is set to Automatic, it loads during boot. As there are too many built-in Windows services, Microsoft first introduced the “delayed start” concept in Windows Vista to improve the Windows boot and login performance. Automatic (delayed start) services won’t start until after all other auto-start services.

Читайте также:  Что такое безопасный режим компьютера windows 10

The service control manager, after processing the auto-start (“Automatic”) services, it then proceeds to launch services that are set to run as Automatic (delayed start) by invoking the ScInitDelayStart() function.

After all the automatic start services are loaded, the system queues the “delay start” services for 2 minutes (120 seconds) by default. This interval can be altered by creating a registry DWORD (32-bit) value named AutoStartDelay and setting the delay (base: decimal) in seconds, in the following registry key:

Other than this, the Service Control Manager loads the “delay start” services in the same way as it starts the non-delayed auto-start services. There are no other differences between Automatic (delayed start) and Automatic startup types.

Delayed Automatic Start for System Services. To address the problem of the growing number of services set to start automatically and the subsequent negative impact on boot performance, there is a new start type for services that do not need to start early in the boot process – the Delayed start. This allows a service to still start automatically, but with the added advantage that boot performance is improved. Services set to start as Delayed will start shortly after boot.

So how does this work? The Service Control Manager starts services that are configured for the delayed automatic start after all of the automatic-start threads have finished starting. The Service Control manager also sets the priority of the initial thread for these delayed services to THREAD_PRIORITY_LOWEST. This causes all of the disk I/O performed by the thread to be a very low priority. Once a service finishes initializing, the priority is set back to normal by the Service Control Manager. The combination of the delayed start, low CPU and memory priority, as well as the background disk priority greatly reduce the interference with the user’s logon.

Many Windows services, including the Background Intelligent Transfer Service (BITS), Windows Update Client, and Windows Media Center, use this new start type to help improve logon performance after a system boot. To configure a service for delayed automatic-start, you can create a REG_DWORD value called DelayedAutoStart in the service’s configuration registry key under HKLM\SYSTEM\CurrentControlSet\Services

Registry values for Automatic and Automatic (delayed start) Startup types

For example, the Delivery Optimization service ( DoSvc ) is set to Automatic (delayed start) in Windows 10 v1903. Here are the registry values for this service which store the service startup type choice:

The DelayedAutostart value data of 1 means the service is set to delayed start. If the value is missing or is set to 0 , then it’s not set to delayed start.

For the Start DWORD value, the possible data are:

  • 2 is Automatic
  • 3 is Manual
  • 4 is Disabled
  • If the Start DWORD is set to anything other than 2 (Automatic), then the DelayedAutoStart value is ignored, even if it’s set to 1 .
  • If the Start DWORD is set to 2 (Automatic) and DelayedAutoStart is set to 0 or the value is missing, then it means the service is set to Automatic start (no delay.)

Editor’s note: Arbitrarily changing the service startup types can cause problems to the system. It’s advisable to leave the services configuration in the Windows default setting in most cases. If you plan to modify the services configuration, backup the current service startup configuration, create a Restore Point, or perform a complete registry backup beforehand.

Оцените статью