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.

Thorarin
  • 47,289
  • 11
  • 75
  • 111
Karol Kolenda
  • 1,660
  • 2
  • 25
  • 37

3 Answers3

2

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
  • 414,610
  • 91
  • 852
  • 789
2
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
  • 31,451
  • 23
  • 97
  • 126
  • 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 Aug 08 '09 at 09:25
  • 3
    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 Aug 08 '09 at 10:40
1

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.

Community
  • 1
  • 1
Thorarin
  • 47,289
  • 11
  • 75
  • 111
  • 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 Aug 08 '09 at 12:15