Reputation: 6924
I have a program that runs another one (let's call the first app Stater and the second app - Worker
).
I use:
process.start();
process.waiForExit();
process.Close();
in Starter.
But, if Starter is forced to close while waiting for Worker (for some extern reason) Worker
will be still in processes, blocking files, eating memory etc.
So, I want to check if Worker
is already running. Before, I will try to start it.
I've tried Process.GetProcessesByName("worker.exe")
but no luck (even if I can see Worker
in Task Manager).
I've seen some topics here about checking every process in memory for its modules, but still, I already know the running file I hope to avoid such solution.
Any advice?
Upvotes: 17
Views: 57585
Reputation: 3956
At the time of starting Worker process, save its ID in your application's configuration/setting file, in this way when you will launch your Starter process, it will first load that ID from settings file and will check if that process is currently running or not. If you want to immediately close Worker process, you can call process.Kill()
on it.
Upvotes: 9
Reputation: 8806
This is much easier...
System.Diagnostics.Process.Start("cmd.exe","/c taskkill /IM notepad.exe");
This code will close the Notepad (if it is running). Type the program name you want to close with it's extension (.exe).
Some applications cannot be stopped without forcing.
Use /F
after taskkill
to force the action.
If you want to close the process tree use /T
after program name.
System.Diagnostics.Process.Start("cmd.exe","/c taskkill /F /IM notepad.exe /T");
Upvotes: 8
Reputation: 437904
If you only need to detect that "worker" is running, a technically much superior solution is have it lock a global mutex for the duration of its lifetime. Any process that knows the mutex name (which is under your control) can then see if the mutex is locked (if it is, worker is running).
However this is not easy to implement correctly as there are many little details you want to get just right; even then, there might be a race condition of "starter" and "worker" are actually launched simultaneously etc (of course this problem, and many others, also apply to all other solutions so it cannot be considered a drawback).
Upvotes: 2
Reputation: 216358
When you call GetProcessesByName("worker") you don't specify exe extension as explained in MSDN
And if you wish to keep a global variable with the process object that you have started you could simply use the process.Kill();
Upvotes: 2
Reputation: 5444
The reason you cannot find it is because you're using .exe. If the executable shows up as worker.exe in TaskManager, just call:
Process[] workers = Process.GetProcessesByName("worker")
foreach (Process worker in workers)
{
worker.Kill();
worker.WaitForExit();
worker.Dispose();
}
Upvotes: 36