Internet. Computer. Help. Adviсe. Repair

Which Windows services are needed and which can be disabled. How to run an application as a Windows service Under what user do services run in Windows?

How to run an application as a Windows service

Is it possible to run a client application as a service? In one of them, I described ways to create a Windows service using standard OS tools. However, not every console application can run as a service, and programs with a graphical interface, in principle, cannot work in this way. But it is still possible to run the application as a service, and a program with an original name will help us with this Non-Sucking Service Manager.

NSSM is free and open source software and supports all Microsoft operating systems from Windows 2000 to Windows 8. NSSM does not require installation, just download and unzip it. The distribution includes versions for 32- and 64-bit operating systems. You can get the program from the website nssm.cc, at the moment the latest stable version is 2.21.1, which I will use.

To demonstrate the capabilities of NSSM, let's try running Windows Notepad as a service on Windows 8.1.

Creating a Service

To create a service named notepad launch the command console, go to the folder with the unpacked NSSM (for 64-bit Windows) and enter the command nssm install notepad, which opens the NSSM graphical installer window. To create a service, just specify the path to the executable file in the Path field and click the “Install service” button. Additionally, in the Options field you can specify the keys required to start the service.

You can also specify some additional parameters when creating a new service.

The Shutdown tab lists the shutdown methods and timeouts used when the application shuts down normally or crashes. When NSSM receives a stop command (for example, when an application is shut down), it attempts to stop the controlled application in a normal manner. If the application does not respond, then NSSM can forcefully terminate all processes and subprocesses of this application.

There are four steps to shutting down the application, and by default they will be used in this order:

In the first stage, NSSM tries to generate and send an event Ctrl+C. This method works well for console applications or scripts, but is not applicable for graphical applications;
NSSM then detects all windows created by the application and sends them a WM_CLOSE message, causing the application to exit;
The third step is that NSSM calculates all threads created by the application and sends them a WM_QUIT message, which will be received if the application has a thread message queue;
As a last resort, NSSM can call the TerminateProcess() method, forcing the application to terminate.

It is possible to disable some or even all methods, but different methods work for different applications and it is recommended to leave everything as is to ensure the application shuts down correctly.

By default, when a service crashes, NSSM tries to restart it. On the “Exit actions” tab, you can change the automatic action when the application terminates abnormally, as well as set a delay before the application automatically restarts.

On the “Input/Output (I/O)” tab, you can set the redirection of application input/output to a specified file.

On the “Environment” tab, you can set new environment variables for the service, or override existing ones.

You can also not use the graphical shell and immediately create a service in the console with the following command:

nssm install notepad ″C:\Windows\system32\notepad.exe″

Service management

After creating the service using NSSM, go to the Services snap-in and find the notepad service. As you can see, in appearance it is no different from other services; we can also start it, stop it, or change the launch mode. However, note that nssm.exe is listed as the executable file.

And if we go to Task Manager, we will see the following picture: NSSM is running as the main (parent) process, the notepad service is running as its child process, and the Notepad application is already running in this child process.

Removing a service

To remove a service, enter the nssm remove notepad command and confirm its removal. And by entering the command nssm remove notepad confirm , you can do without confirmation.

Start a service interactively

The main difference between a user application and a service is that, once launched, the application may require additional user actions to continue running, such as pressing a button or entering a command. To do this, you need to gain access to it, which, as it turns out, is not so easy to do.

In order to start a service in interactive mode, you need to open its properties in the Services snap-in and on the “Login” tab, check the “Allow interaction with the desktop” checkbox.

And then miracles begin :) A service launched in interactive mode opens in an isolated session (session 0). This session can only be accessed by using the Interactive Services Detection Service (ui0detect), which monitors the startup of interactive services on the computer and issues an alert. In Windows 7\Server 2008 this service is active by default, but in Windows 8\Server 2012 it is disabled and does not appear in the Services graphical snap-in (at least I did not find it there). Moreover, if you do find this mysterious service and try to start it, you will receive an error message.

But the fact is that to run it, you must allow interactive services to run on your computer. Therefore, open the registry editor, find in the HKLM\System\CurrentControlSet\Control\Windows section a DWORD type parameter named NoInteractiveServices and set its value to 0 .

Then open the PowerShell console and start the discovery service with the command:

Start-Service -Name ui0detect

After making sure that the detection service is running, we restart the notepad service, and we get this window. Select “View message”

and we find ourselves in the null session in which our application runs. Then we perform the necessary actions with it and return back.

This is an interesting solution for running applications as Windows services. Not the most beautiful, but quite consistent with its name :)

You can configure the operation of services in a special Windows manager. To open it, use the Windows + R key combination, enter services.msc in the line that appears and press Enter. You will see the same or similar (if you have one of the older OS versions) window:

The manager displays services in table form. Here you can view a list of available services, read their brief descriptions, and find out their current status. Of particular importance is the “Startup Type” column. It is he who shows whether a specific service is enabled and in what mode it is launched by the system.

By double-clicking on one of the services, you will open a window in which you can disable it. Just open the “Startup Type” item, select “Disabled” and click “OK”. But among other launch options there is a “Manual” value. For security reasons, select this for all services that you want to disable. This will allow the system to start services when they are really needed, and not waste time on them the rest of the time.

Do not disable services completely, but only switch them to manual mode.

The services listed below are not critical to the operation of the system, and many users can do without them. Therefore, you can set these services to manual mode. Be sure to read the summary before making changes so you don't interrupt services that matter to you.

Some services on our list may already be completely disabled on your PC or initially work in manual mode. In that case, just skip them.

Incorrect actions during the process of configuring services can lead to incorrect operation of the system. By making changes, you take responsibility.

For the changes to take effect, be sure to restart your PC after configuration.

Windows services that can be switched to manual mode

The Russian names of some services on this list may differ from those that you see on your computer. But this only applies to wording. If you cannot find the service you need by its exact name, look for options that are similar in meaning.

Windows 10

  • Functionality for connected users and telemetry (Connected User Experiences and Telemetry).
  • Diagnostic Tracking Service.
  • dmwappushsvc.
  • Downloaded Maps Manager - if you are not using the Maps application.
  • Touch Keyboard and Handwriting Panel Service.
  • Windows Defender Service.

Windows 8/8.1

  • Diagnostic Policy Service.
  • Distributed Link Tracking Client - if the computer is not connected to any network.
  • IP Helper - if you are not using an IPv6 connection.
  • Program Compatibility Assistant Service.
  • Print Spooler - if you don't have a printer.
  • Remote Registry - this service can be completely disabled.
  • Secondary Logon.
  • Security Center.
  • NetBIOS support module over TCP/IP (TCP/IP NetBIOS Helper).
  • Windows Error Reporting Service.
  • Windows Image Acquisition (WIA) - if you don't have a scanner.
  • Windows Search - if you don't use Windows Search.

Windows 7

  • Computer Browser - if the computer is not connected to any network.
  • Diagnostic Policy Service.
  • Distributed Link Tracking Client - if the computer is not connected to any network.
  • IP Helper - if you are not using an IPv6 connection.
  • Offline Files.
  • Portable Device Enumerator Service.
  • Print Spooler - if you don't have a printer.
  • Protected Storage.
  • Remote Registry - this service can be completely disabled.
  • Secondary Logon.
  • Security Center.
  • Server - if the computer is not used as a server.
  • NetBIOS support module over TCP/IP (TCP/IP NetBIOS Helper).
  • Windows Error Reporting Service.
  • Windows Search - if you don't use Windows Search.

Windows Vista

  • Computer Browser - if the computer is not connected to any network.
  • Desktop Window Manager Session Manager - if you are not using the Aero theme.
  • Diagnostic Policy Service.
  • Distributed Link Tracking Client - if the computer is not connected to any network.
  • Offline Files.
  • Portable Device Enumerator Service.
  • Print Spooler - if you don't have a printer.
  • ReadyBoost.
  • Remote Registry - this service can be completely disabled.
  • Secondary Logon.
  • Security Center.
  • Server - if the computer is not used as a server.
  • Tablet PC Input Service.
  • NetBIOS support module over TCP/IP (TCP/IP NetBIOS Helper).
  • Themes - if you are using the classic Windows theme.
  • Windows Error Reporting Service.
  • Windows Media Center Service Launcher.
  • Windows Search - if you don't use Windows Search.

Windows XP

  • Alerter.
  • Computer Browser - if the computer is not connected to any network.
  • Distributed Link Tracking Client - if the computer is not connected to any network.
  • Indexing Service - if you don't use Windows Search.
  • Internet Firewall (ICF) / Internet Connection Sharing (ICS).
  • Messenger service.
  • Remote Registry - this service can be completely disabled.
  • Secondary Logon.
  • Server - if the computer is not used as a server.
  • System Restore service.
  • NetBIOS support module over TCP/IP (TCP/IP NetBIOS Helper).
  • Uninterruptible Power Supply.
  • Upload Manager.
  • Wireless configuration (Wireless Zero Configuration).

Last updated: 10/31/2015

One of the most important components of the Windows OS is services. In fact, these are separate applications that do not have a graphical interface and that perform various tasks in the background. Services can be started when the operating system starts, or at any other time the user is working. A common example of services are various web servers that listen in the background to a specific port for connections, and if there are connections, they interact with them. It can also be various auxiliary update services for other installed programs that contact the server to find out if there is a new version of the application. In general, we can open the services panel and see for ourselves all installed and running services:

Let's look at how to create your own services in C#. As the task to be implemented, we will choose to monitor changes in a specific folder in the file system. Now let's create a service to execute it.

First, let's create a new project, which will be of type Windows Service. Let's call the project FileWatcherService:

Visual Studio then generates a project that has everything you need. While we don't necessarily need to choose this type of project, we could create a class library project and then define all the necessary classes in it.

So the new project looks like this:

There is also a file Program.cs and there is the actual service node Service1.cs.

The service represents a normal application, but it does not start on its own. All calls and access to it go through the service control manager (Service Control Manager or SCM). When a service starts automatically at system startup or manually, SCM calls the Main method in the Program class:

Static class Program ( static void Main() ( ServiceBase ServicesToRun; ServicesToRun = new ServiceBase ( new Service1() ); ServiceBase.Run(ServicesToRun); ) )

The Main method is defined by default to run multiple services at once, which are defined in the ServicesToRun array. However, by default the project contains only one service, Service1. The launch itself is carried out using the Run method: ServiceBase.Run(ServicesToRun) .

The service being started is represented by the Service1.cs node. However, this is not actually a simple code file. If we open this node, we will see the service designer file Service1.Designer.cs and the Service1 class.

The Service1 class actually represents the service. By default it has the following code:

Using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Linq; using System.ServiceProcess; using System.Text; using System.Threading.Tasks; namespace FileWatcherService ( public partial class Service1: ServiceBase ( public Service1() ( InitializeComponent(); ) protected override void OnStart(string args) ( ) protected override void OnStop() ( ) ) )

The service class must inherit from the ServiceBase base class. This class defines a number of methods, the most important of which are the OnStart() method, which starts the actions performed by the service, and the OnStop() method, which stops the service.

After SCM calls the Main method and registers the service, it is directly called by running the OnStart method.

When we send a command to stop a service in the services console or through the command line, SCM calls the OnStop method to stop it.

In addition to these two methods in the service class, you can override several more methods of the ServiceBase base class:

    OnPause: Called when the service is paused

    OnContinue: Called when a service resumes after it has been suspended

    OnShutdown: Called when Windows shuts down

    OnPowerEvent: Called when the power mode changes

    OnCustomCommand: Called when a service receives a custom command from the Service Control Manager (SCM)

In the constructor of the Service1 class, the InitializeComponent() method is called, which is defined in the designer file Service1.Designer.cs:

Namespace FileWatcherService ( partial class Service1 ( private System.ComponentModel.IContainer components = null; protected override void Dispose(bool disposing) ( if (disposing && (components != null)) ( components.Dispose(); ) base.Dispose(disposing ); ) private void InitializeComponent() ( components = new System.ComponentModel.Container(); this.ServiceName = "Service1"; ) ) )

The only thing that needs to be noted in it is setting the name of the service (ServiceName property):

This.ServiceName = "Service1";

This is the name that will be displayed in the services console after installing this service. We can change it, or we can leave it as it is.

Now let's change the service code as follows:

Using System; using System.ServiceProcess; using System.IO; using System.Threading; namespace FileWatcherService ( public partial class Service1: ServiceBase ( Logger logger; public Service1() ( InitializeComponent(); this.CanStop = true; this.CanPauseAndContinue = true; this.AutoLog = true; ) protected override void OnStart(string args) ( logger = new Logger(); Thread loggerThread = new Thread(new ThreadStart(logger.Start)); loggerThread.Start(); ) protected override void OnStop() ( logger.Stop(); Thread.Sleep(1000); ) ) class Logger ( FileSystemWatcher watcher; object obj = new object(); bool enabled = true; public Logger() ( watcher = new FileSystemWatcher("D:\\Temp"); watcher.Deleted += Watcher_Deleted; watcher.Created + = Watcher_Created; watcher.Changed += Watcher_Changed; watcher.Renamed += Watcher_Renamed; ) public void Start() ( watcher.EnableRaisingEvents = true; while(enabled) ( Thread.Sleep(1000); ) ) public void Stop() ( watcher.EnableRaisingEvents = false; enabled = false; ) // renaming files private void Watcher_Renamed(object sender, RenamedEventArgs e) ( string fileEvent = "renamed to " + e.FullPath; string filePath = e.OldFullPath; RecordEntry(fileEvent, filePath); ) // changing files private void Watcher_Changed(object sender, FileSystemEventArgs e) ( string fileEvent = "changed"; string filePath = e.FullPath; RecordEntry(fileEvent, filePath); ) // creating files private void Watcher_Created(object sender, FileSystemEventArgs e) ( string fileEvent = "created"; string filePath = e.FullPath; RecordEntry(fileEvent, filePath); ) // deleting files private void Watcher_Deleted(object sender, FileSystemEventArgs e) ( string fileEvent = "deleted"; string filePath = e.FullPath; RecordEntry(fileEvent, filePath); ) private void RecordEntry(string fileEvent, string filePath) ( lock (obj) ( using (StreamWriter writer = new StreamWriter("D:\\templog.txt", true)) ( writer.WriteLine(String.Format("(0) file (1) was (2)", DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss"), filePath, fileEvent)); writer. Flush(); ) ) ) ) )

The key class that encapsulates all the functionality is the Logger class. Using the FileSystemWatcher object, it will monitor changes in the folder D://Temp. The Start() method specifies that we will watch for changes through the FileSystemWatcher object. And all the work will continue as long as the enabled boolean variable is true . And the Stop() method will allow the class to terminate.

FileSystemWatcher events allow you to monitor all changes to a watched folder. This will record changes to the templog.txt file. To avoid resource race for the templog.txt file, into which changes are recorded, the recording procedure is blocked by the lock(obj) stub.

As a result, after creating, changing, renaming and deleting, the log file will contain something like:

07/30/2015 12:15:40 file D:\Temp\New text document.txt was created 07/30/2015 12:15:46 file D:\Temp\New text document.txt was renamed to D:\Temp\hello. txt 07/30/2015 12:15:55 file D:\Temp\hello.txt was modified 07/30/2015 12:15:55 file D:\Temp\hello.txt was modified 07/30/2015 12:16:01 file D: \Temp\hello.txt has been deleted

In the Service1 service class itself, a number of options are set in the constructor:

This.CanStop = true; // the service can be stopped this.CanPauseAndContinue = true; // the service can be paused and then continued this.AutoLog = true; // the service can write to the log

In the OnStart() method, a new thread is called to start the Logger object:

Protected override void OnStart(string args) ( logger = new Logger(); Thread loggerThread = new Thread(new ThreadStart(logger.Start)); loggerThread.Start(); )

The new thread is needed because the current thread only processes SCM commands and must return from the OnStart method as quickly as possible.

When a command is received from the SCM to stop the service, the OnStop method is triggered, which calls the logger.Stop() method. The additional delay will allow the logger thread to stop:

Protected override void OnStop() ( logger.Stop(); Thread.Sleep(1000); )

However, the service class itself is not enough. We also need to create a service installer.

From a software compatibility point of view. So it's only natural that we come back to discussing services in the context of Windows 7. But this time we'll talk about some of the benefits of optimizing the services available in Windows 7. This article is about a new feature in Windows 7 - Trigger Start Services. But before we look at the API, let's take a look at the big picture of the services.

What are services?

A service is an internal mechanism built into the Windows operating system. You can think of services as special applications that run regardless of the current user context. Services differ from regular applications in that they can be configured to operate from the moment the system is turned on (booted) until shutdown, without requiring user presence. That is, services can run even if the user is not logged in.

We prefer to think of services as running tasks that run in the background and do not affect user operations. Services in Windows are responsible for all types of background activity, from Remote Procedure Call (RPC), Printer Spooler and all the way to Network Location Awareness.

Over the years, Windows has grown and so have the number of services. Let's be honest, background services in Windows are a bit of a pain - the operating system comes with a lot of services out of the box. In addition, independent software developers (ISVs) and their applications are adding even more services. For example, software update services. However, some services are critical and are required during the boot process, while others are needed later when a specific user logs in, and others do not need to start at all until they are called. Despite this, when you look at the list of currently running services, you see many objects that do not need to work 24x7.

What's wrong with services that operate 24 hours a day, 7 days a week?

There are several problems associated with 24x7 services. Firstly, why should something be running (even in the background) if it is not needed? Any running process (including services) uses up precious memory and CPU resources that could be used for other applications and services. If you count all the services running at a given moment, they add up to a significant amount of memory, handles, threads, and CPU usage. All of these "wasted" resources reduce the overall performance of the computer, reduce its responsiveness, and make the computer appear sluggish and slow. In addition, since many services are configured to start automatically (start working when the system starts), they affect the boot time of the computer.

Secondly, these wasted resources have a direct impact on energy consumption. The greater the load on the CPU, the more power the computer consumes. This can be critical on laptops and can reduce battery life by several hours.

Third, running unproductive software continuously can lead to memory leaks and overall system instability. This leads to the failure of applications and, ultimately, the computer.

Finally, if the service operates 24x7, and if it is a well-known service (which every popular application might have, such as PDF Reader), then this creates a large attack surface. An attacker could use information that a certain popular application installs a 24x7 service and try to hack it to gain access to the computer.

With all that said, you might be wondering why so many developers set up their services to run all the time if they have another option. Even before Windows 7, there were several options available to start services:

  • Disabled completely disables a service and prevents it and dependent services from starting - meaning the user must enable the service manually from Control Panel or Command Prompt
  • Manual starts a service as needed (due to dependencies of other services) or when the service is called from the application using the appropriate APIs, as will be shown below
  • Automatic starts a service upon login
  • Automatic Delayed– a newer type of startup introduced in Windows Vista, with which the service starts after the boot has completed and the initial operations have been completed, which speeds up the system startup.

Unfortunately, many ISVs (including Microsoft itself) continue to set their services to Automated or Automatic Delayed because it seems like the simplest solution for everyone. The service simply runs 24x7 and is always available, eliminating any need to check dependencies or whether the service is running.

There are many examples of existing services that can use much less resources and become safer without working 24x7. For example, think about an update service that checks for new updates to an application. If the computer is not connected to the network and does not have an IP address, why should it work? It can't do anything, so why leave a program running that doesn't do anything? Think about the Policy Management Service, which is used when changing Group Policies or when a computer joins or leaves a domain, but now that the computer is connected to my home network, the service, again, runs on empty.

The emergence of trigger-based services

The solution to the above problems is to move the service out of the "always on state" to other types of background activity, such as scheduled tasks or triggered services. This article is about Windows 7 Trigger Start Services. A lot of interesting things can be said about Windows 7 Scheduled Tasks, which will be done in subsequent articles.

Is it possible to run a client application as a service? Not every console application can run as a service, and programs with a graphical interface, in principle, cannot work in this way. But it is still possible to run the application as a service, and a program with an original name will help us with this Non-Sucking Service Manager.

NSSM is free and open source software and supports all operating systems Microsoft, starting with Windows 2000 and ending with . NSSM does not require installation, just download and unpack it. The distribution includes versions for 32- and 64-bit operating systems. You can get the program from the website nssm.cc, at the moment the latest stable version is 2.21.1, which I will use.

To demonstrate the capabilities of NSSM, let's try to run Notepad as a service on .

Creating a Service

To create a service named notepad launch the command console, go to the folder with the unpacked NSSM (for 64-bit Windows) and enter the nssm install notepad command, which opens the NSSM graphical installer window. To create a service, just specify the path to the executable file in the Path field and click the "Install service" button. Additionally, in the Options field you can specify the keys required to start the service.

You can also specify some additional parameters when creating a new service.

The "Shutdown" tab lists the shutdown methods and timeouts used when the application shuts down normally or crashes. When NSSM receives a stop command (for example, when an application is shut down), it attempts to stop the controlled application in a normal manner. If the application does not respond, then NSSM can forcefully terminate all processes and subprocesses of this application.

There are four steps to shutting down the application, and by default they will be used in this order:

In the first stage, NSSM tries to generate and send an event Ctrl+C. This method works well for console applications or scripts, but is not applicable for graphical applications;
NSSM then detects all windows created by the application and sends them a WM_CLOSE message, causing the application to exit;
The third step is that NSSM calculates all threads created by the application and sends them a WM_QUIT message, which will be received if the application has a thread message queue;
As a last resort, NSSM can call the TerminateProcess() method, forcing the application to terminate.

It is possible to disable some or even all methods, but different methods work for different applications and it is recommended to leave everything as is to ensure the application shuts down correctly.

By default, when a service crashes, NSSM tries to restart it. On the "Exit actions" tab, you can change the automatic action when the application terminates abnormally, as well as set a delay before the application automatically restarts.

On the "Input/Output (I/O)" tab, you can set the redirection of application input/output to a specified file.

On the "Environment" tab, you can set new environment variables for the service, or override existing ones.

You can also not use the graphical shell and immediately create a service in the console with the following command:

nssm install notepad ″C:\Windows\system32\notepad.exe″

Service management

After creating the service using NSSM, go to the Services snap-in and find the notepad service. As you can see, in appearance it is no different from other services; we can also start it, stop it, or change the launch mode. However, note that nssm.exe is listed as the executable file.

And if we go to Task Manager, we will see the following picture: NSSM is running as the main (parent) process, the notepad service is running as its child process, and the Notepad application is already running in this child process.

Removing a service

To remove a service, enter the nssm remove notepad command and confirm its removal. And by entering the command nssm remove notepad confirm, you can do without confirmation.

Start a service interactively

The main difference between a user application and a service is that, once launched, the application may require additional actions from the user to continue running - for example, pressing a button or entering a command. To do this, you need to gain access to it, which, as it turns out, is not so easy to do.

In order to start a service in interactive mode, you need to open its properties in the Services snap-in and on the “Login” tab, check the “Allow interaction with the desktop” checkbox.

And then the miracles begin. For a service running in interactive mode, the system opens a separate isolated session (session 0). This session can only be accessed by using the Interactive Services Detection Service (ui0detect), which monitors the startup of interactive services on the computer and issues an alert. In Windows 7\Server 2008 this service is active by default, but in Windows 8\Server 2012 it is disabled and does not appear in the Services graphical snap-in (at least I did not find it there). Moreover, if you do find this mysterious service and try to start it, you will receive an error message.

But the fact is that to run it, you must allow interactive services to run on your computer. Therefore, open the registry editor, find in the HKLM\System\CurrentControlSet\Control\Windows section a DWORD type parameter named NoInteractiveServices and set its value to 0 .

Then open the PowerShell console and start the discovery service with the command:

Start-Service -Name ui0detect

After making sure that the detection service is running, we restart the notepad service, and we get this window. Select "View message"

and we find ourselves in the null session in which our application runs. Then we perform the necessary actions with it and return back.

This is an interesting solution for running applications as Windows services. Not the most beautiful, but quite consistent with its name

Did you like the article? Share with your friends!
Was this article helpful?
Yes
No
Thanks for your feedback!
Something went wrong and your vote was not counted.
Thank you. Your message has been sent
Found an error in the text?
Select it, click Ctrl + Enter and we will fix everything!