Windows service from executable

Modifying the “Path to executable” of a windows service

I’d like to modify the path to my application, but doing so breaks it because the service still points to the old location.

By going to Administrative Tools > Services you can open a properties dialog and view the Path to executable , but there is no way to change it.

Is there any way a user can modify the service path without having to reinstall the application ?

8 Answers 8

There is also this approach seen on SuperUser which uses the sc command line instead of modifying the registry:

Note: the space after binPath= is important. You can also query the current configuration using:

This displays output similar to:

It involves editing the registry, but service information can be found in HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services . Find the service you want to redirect, locate the ImagePath subkey and change that value.

You could also do it with PowerShell:

Open Run(win+R) , type «Regedit.exe» , to open «Registry Editor», go to

HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services

find «Apache2.4» open the folder find the «ImagePath» in the right side, open «ImagePath» under «value Data» put the following path:

«C:\xampp\apache\bin\httpd.exe» -k runservice foe XAMPP for others point to the location where Apache is installed and inside locate the bin folder «C:(Apache installed location)\bin\httpd.exe» -k runservice

Slight modification to this @CodeMaker ‘s answer, for anyone like me who is trying to modify a MongoDB service to use authentication.

When I looked at the «Path to executable» in «Services» the executed line already contained speech marks. So I had to make minor modification to his example.

  1. Type Services in Windows
  2. Find MongoDB (or the service you want to change) and open the service, making sure to stop it.
  3. Make a note of the Service Name (not the display name)
  4. Look up and copy the «Path to executable» and copy it.

For me the path was (note the speech marks)

Antimalware Service Executable что это и почему грузит ЦП Windows 10

Что за процесс «Antimalware Service Executable » и как исправить высокую загрузку процессора и диска в Windows 10.

Если вы заметили, что процесс Antimalware Sevice Executable имеет высокую загрузки ЦП и диска в Windows 10, будьте уверены, вы не одиноки. Многие пользователи Windows 10 также сообщают об этой проблеме. Что еще более важно, вы можете решить эту проблему самостоятельно, не обращаясь к специалисту за помощью.

В этой статье вы узнаете, что это за процесс Antimalware Sevice Executable и как устранить проблему с высокой загрузкой процессора.

Что такое Antimalware Service Executable?

Antimalware Service Executable — это процесс который выполняет фоновую проверку вашей системы на наличие вирусов.

Возможно, вы знакомы с Защитник Windows, это антивирусное программное обеспечение, встроенное в Windows 10. Исполняемый файл службы защиты от вредоносных программ является одной из фоновых служб Защитника Windows. Он также известен как MsMpEng.exe, вы можете найти его на вкладке Детали в вашем диспетчере задач.

Читайте также:  Администрирование windows 10 cmd

Исполняемый файл службы защиты от вредоносных программ работает для сканирования вредоносных и шпионских программ при доступе к ним. Он обнаружит, если есть что-то вредное. Кроме того, он также выполняет фоновую проверку вашей системы на наличие вирусов или червей. Сканирование в значительной степени зависит от процессора вашего компьютера, поэтому вы обнаруживаете, что он использует процессор в ваших Windows 10.

Как исправить «Antimalware Service Executable» грузит систему

Способ 1: Изменить расписания Защитника Windows

Ошибка в основном из-за функции защиты в режиме реального времени. Таким образом, мы можем изменить расписание Защитника Windows, чтобы исправить это.

  1. На клавиатуре одновременно нажмите клавишу с логотипом Windows и клавишу R, чтобы вызвать окно «Выполнить».
  2. Введите taskschd.msc и нажмите Enter.

Дважды щелкните «Библиотека планировщика заданий» > «Microsoft» > «Windows».

Дважды щелкните «Windows Defender» в Windows. Затем дважды щелкните по «Windows Defender Scheduled Scan».

Снимите все пункты во вкладке «Условия». Затем нажмите ОК.

С выполнением вышеуказанных пунктов, процесс Antimalware Service должен перестать грузить систему Windows​.

Если к сожалению не помогло, пожалуйста, не расстраивайтесь, попробуйте следующий способ.

Способ 2: Добавьте Antimalware Service Executable в список исключений Защитника Windows

  1. На клавиатуре одновременно нажмите логотип Windows + i, чтобы открыть окно настроек.
  2. Нажмите Обновление и безопасность.

В центре безопасности откройте страницу настройки защиты от вирусов и угроз, а на ней нажмите «Параметры защиты от вирусов и других угроз».

  • Внизу следующей страницы, в разделе «Исключения» нажмите «Добавление или удаление исключений».
  • Нажмите «Добавить исключение».
  • Нажмите Исключить процесс.
  • Введите MsMpEng.exe. Затем нажмите ОК.
  • Теперь вы добавили Antimalware Service в список исключений Защитника Windows. Ошибка должна быть исправлена.

    Если этих 2 способа не помогли, попробуйте отключить Защитник Windows.

    How to make a Windows Service from .NET Core 2.1/2.2

    Recently I had a need to convert a .NET Core 2.1 or 2.2 console application into a Windows Service.

    As I didn’t have a requirement to port this process to Linux, I could dispense with the multiple platform solutions that I had seen on Stack Overflow that dealt with any combination of .NET Framework, .NET Standard and .NET Core.

    3 Answers 3

    In this post I will describe the steps required to set up a .NET Core 2.1 or 2.2 process as a Windows Service.

    As I have no requirement for Linux, I could look for a solution that was Windows-specific.

    A bit of digging turned up some posts from Steve Gordon (thanks!), in particular where he presents the Microsoft.Extensions.Hosting package and Windows hosting (click here for post and here for his GitHub sample).

    Here are the steps required:

    • First create a .NET Core console application.
    • Set the language version to at least 7.1 to support async Task for the Main method. (Access the language version from the project settings->Build->Advanced->Language Settings.
    • Add the Microsoft.Extensions.Hosting and the System.ServiceProcess.ServiceController packages.
    • Edit the project .csproj file and include in the PropertyGroup: win7-x64
    • Ensure you have in the PropertyGroup Exe

    Now go to Program.cs and copy the following:

    This code will support interactive debugging and production execution, and runs the example class LoggingService.

    Here is a skeleton example of the service itself:

    The final two files necessary to complete the project:

    File ServiceBaseLifetime.cs:

    File ServiceBaseLifetimeHostExtensions.cs:

    In order to install, run or delete the service I use the ‘sc’ utility:

    where AdvancedHost is the service name and the value for binPath is the compiled executable.

    Once the service is created, to start:

    And finally to delete (once stopped):

    There are many more features contained in sc; just type ‘sc’ alone on the command line.

    The results of sc can be seen in the services Windows control panel.

    Читайте также:  Как убрать вы стали жертвой подделки windows

    How do I run another executable from a Windows service

    Besides a few tutorials on Go I have no actual experience in it. I’m trying to take a project written in Go and converting it into a windows service.

    I honestly haven’t tried anything besides trying to find things to read over. I have found a few threads and choosen the best library I felt covered all of our needs

    So I spent some time going over this code. Tested it out to see what it does. It performs as it should.

    The question I have is we currently have a Go program that takes in arguments and for our service we pass in server. Which spins up our stuff on a localhost webpage.

    I believe the code above may have something to do with that but I’m lost at how I would actually get it spin off our exe with the correct arguements. Is this the right spot to call main?

    Im sorry if this is vague. I dont know exactly how to make this interact with our already exisiting exe.

    I can get that modified if I know what needs to be changed. I appreacite any help.

    1 Answer 1

    OK, that’s much clearer now. Well, ideally you should start with some tutorial on what constitutes a Windows service—I bet tihis might have solved the problem for you. But let’s try anyway.

    Some theory

    A Windows service sort of has two facets: it performs some useful task and it communicates with the SCM facility. When you manipulate a service using the sc command or through the Control Panel, you have that piece of software to talk with SCM on your behalf, and SCM talks with that service.

    The exact protocol the SCM and a service use is low-level and complicated and the point of the Go package you’re using is to hide that complexity from you and offer a reasonably Go-centric interface to that stuff.

    As you might gather from your own example, the Execute method of the type you’ve created is—for the most part—concerned with communicating with SCM: it runs an endless for loop which on each iteration sleeps on reading from the r channel, and that channel delivers SCM commands to your service.

    So you basically have what could be called «an SCM command processing loop».

    Now recall those two facets above. You already have one of them: your service interacts with SCM, so you need another one—the code which actually performs useful tasks.

    In fact, it’s already partially there: the example code you’ve grabbed creates a time ticker which provides a channel on which it delivers a value when another tick passes. The for loop in the Execute method reads from that channel as well, «doing work» each time another tick is signalled.

    OK, this is fine for a toy example but lame for a real work.

    Approaching the solution

    So let’s pause for a moment and think about our requirements.

    1. We need some code running and doing our actual task(s).
    2. We need the existing command processing loop to continue working.
    3. We need these two pieces of code to work concurrently.

    In this toy example the 3rd point is there «for free» because a time ticker carries out the task of waiting for the next tick automatically and fully concurrently with the rest of the code.

    Your real code most probably won’t have that luxury, so what do you do?

    In Go, when you need to do something concurrently with something else, an obvious answer is «use a goroutine».

    Читайте также:  Драйвер для принтера самсунг scx 3400 для линукс

    So the first step is to grab your existing code, turn it into a callable function and then call it in a separate goroutine right before entering the for loop. This way, you’ll have both pieces run concurrently.

    The hard parts

    OK, that wasn’t hard.

    The hard parts are:

    • How to configure the code which performs the tasks.
    • How to make the SCM command processing loop and the code carrying out tasks communicate.

    Configuration

    This one really depends on the policies at your $dayjob or of your $current_project, but there are few hints:

    A Windows service may receive command-line arguments—either for a single run or permanently (passed to the service on each of its runs).

    The downside is that it’s not convenient to work with them from the UI/UX standpoint.

    Typically Windows services used to read the registry.

    These days (after the advent of .NET and its pervasive xml-ity) the services tend to read configuration files.

    The OS environment most of the time is a bad fit for the task.

    You may combine several of these venues.

    I think I’d start with a configuration file but then again, you should pick the path of the least resistance, I think.

    One of the things to keep in mind is that the reading and processing of the configuration should better be done before the service signals the SCM it started OK: if the configuration is invalid or cannot be loaded, the service should extensively log that and signal it failed, and not run the actual task processing code.

    Communication between the command processing loop and the tasks carrying code

    This is IMO the hardest part.

    It’s possible to write a whole book here but let’s keep it simple for now.

    To make it as simple as possible I’d do the following:

    • Consider pausing, stopping and shutting down mostly the same: all these signals must tell your task processing code to quit, and then wait for it to actually do that.
    • Consider the «continue» signal the same as starting the task processing function: run it again—in a new goroutine.
    • Have a one-directional communication: from the control loop to the tasks processing code, but not the other way—this will greatly simplify service state management.

    This way, you may create a single channel which the task processing code listens on—or checks periodically, and when a value comes from that channel, the code stops running, closes the channel and exits.

    The control loop, when the SCM tells it to pause or stop or shut down, sends anything on that channel then waits for it to close. When that happens, it knows the tasks processing code is finished.

    In Go, a paradigm for a channel which is only used for signaling, is to have a channel of type struct<> (an empty struct ).

    The question of how to monitor this control channel in the tasks running code is an open one and heavily depends on the nature of the tasks it performs.

    Any further help here would be reciting what’s written in the Go books on concurrency so you should have that covered first.

    There’s also an interesting question of how to have the communication between the control loop and the tasks processing loop resilient to the possible processing stalls in the latter, but then again, IMO it’s too early to touch upon that.

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