How to stop a process in C # knowing its name?

I have a program that launches another (allows you to call the first Stater application and the second application - Worker).

I use

process.start(); process.waiForExit(); process.Close(); 

in the starter.

But if Starter is forced to close, waiting for the Worker (for some reason), the Worker will still be in the process, blocking files, there is memory, etc.

So, I want to check if Worker is working before I try to start it. I tried Process.GetProcessesByName ("worker.exe") but no luck (even if I see Worker in the task manager).

I saw here several topics about checking each process in memory for my modules, but still I already know that the file is working, which I hope to avoid such a solution.

Any tips?

+4
source share
5 answers

When starting a workflow, save its identifier in the configuration / application settings file, so when you start your starting process, it will first load this identifier from the settings file and check whether this process is currently working or not. If you want to close the workflow immediately, you can call process.Kill() on it.

+4
source

The reason you cannot find it is because you are using .exe. If the executable is displayed in the work.exe file in the TaskManager, simply call:

 Process[] workers = Process.GetProcessesByName("worker") foreach (Process worker in workers) { worker.Kill(); worker.WaitForExit(); worker.Dispose(); } 
+12
source

It is much easier ...

 System.Diagnostics.Process.Start("cmd.exe","/c taskkill /IM notepad.exe"); 

This code will close Notepad (if it is running). Enter the name of the program you want to close with the extension (.exe).

Some applications cannot be stopped without coercion. Use /F after taskkill to force the action. If you want to close the process tree, use /T after the program name.

 System.Diagnostics.Process.Start("cmd.exe","/c taskkill /F /IM notepad.exe /T"); 
+4
source

When you call GetProcessesByName ("worker") , you do not specify the exe extension as described in MSDN
And if you want to save a global variable with the initial object of the process, you can simply use process.Kill ();

+2
source

If you only need to find that the β€œworker” is running, a technically superior solution has a global mutex lock for its entire lifetime. Any process that knows the name of the mutex (which is under your control) can then see if the mutex is locked (if there is one, the worker is working).

However, this is not easy to implement correctly , as there are many small parts that you want to get correctly; even then there may be a race condition "starter" and "worker" actually start simultaneously, etc. (of course, this problem and many others are also applicable to all other solutions, therefore it cannot be considered a drawback).

+2
source

Source: https://habr.com/ru/post/1401132/


All Articles