tags:

views:

91

answers:

3

How can I list and terminate existing processes in .Net application? Target applications are 1) .Net applications, 2) they are instances of the same executable 3) they have unique Ids but I don't know how to get this information from them, 4) they are spawned externally (i.e. I do not have handles to them as I don't create them).

I want to list all processes, get unique ids from them and restart some of them. I assume that all of them are responsive.

+2  A: 

You can grab a list of running processes with Process.GetProcesses static method. You can easily query the return value (possibly with LINQ) to get the ones you want.

System.Diagnostics.Process.GetProcesses()
Mehrdad Afshari
+2  A: 
Process.Kill();

Check this out for killing processes: http://www.dreamincode.net/code/snippet1543.htm

The Process Id is a property of the process. Eg:

Process.Id

All of the methods available on the process are listed here: http://msdn.microsoft.com/en-us/library/system.diagnostics.process_methods.aspx

grenade
Thanks Rob, this almost solve my problem. Now I just need some way to get process identity (some basic interprocess communication). Any idea how to do this i.e. how to request a single string from the processes listed by GetProcesses?
Karol Kolenda
Since some kind of interprocess communication is needed anyway, `Process.Kill()` should be unnecessary. Implement some way for the process to shut down gracefully.
Thorarin
Agreed. +1 on your answer.
grenade
+1  A: 

I'd like to refer you to this question on interprocess communication, and also this tutorial. You can use WCF to query a process, and request a shutdown. Each process will need it's own named pipe. You can generate a unique name at startup, based on the process ID (Process.GetCurrentProcess().Id).

All this may be a little heavy weight for some simple communication though. Using the Windows message queue might be an option as well. You can use process.MainWindowHandle to get a process' window handle and send custom messages to instances of your application. See Messages and Message queues. If you choose to go that way, pinvoke could be of help.

Thorarin
My spawned processes already using WCF over named pipes! I just didn't think about naming pipes based on process Ids. Brilliant idea! This is a perfect solution for me. (Messages and pinvoke are not really reliable on >= Vista systems - UAC tends to isolate them unless running as admin).
Karol Kolenda
Even between processes running as the same user? How annoying...
Thorarin