tags:

views:

238

answers:

2

Scenario

I have a method that returns a list of processes using WMI. If I have 3 processes running (all of which are C# applications) - and they all have THE SAME PROCESS NAME but different command line arguments, how can I differentiate between them If I want to start them or terminate them!?

Thoughts

As far as I can see, I physically cannot differentiate between them, at least not without having to use the Handle, but that doesn't tell me which one of them got terminated because the others will still sit there with the same name........

....really stumped, help greatly appreciated!

A: 

The WMI Win32_ProcessObject has a CommandLine property you could use if that is what you know differentiates the instances.

string query = “Select * From Win32_Process Where Name = “ + processName;
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection processList = searcher.Get();

foreach (ManagementObject obj in processList)
{
     string cmdLine = obj.GetPropertyValue("CommandLine").ToString();

     if (cmdLine == "target command line options")
     {
          // do work
     }
}
mjmarsh
Be aware that you need `SeDebugPrivilege` to read `Win32_Process.CommandLine`, so it is usually not possible to read this property remotely.
Anton Tykhyy
+1  A: 

Create the process using a technique that gives you the process ID as an out parameter. E.g.

Then you can use that value to truly know which version of the process you want to kill later. E.g.

  • WMI: Get Win32_Process instance matching ProcessId, call Terminate()
  • .NET: Get Process instance using GetProcessById, call Kill and then WaitForExit

(Note that if the process stops before you kill it, the OS can assign that same process ID to a new process, so of course you'll want to double check that you're killing the right one, e.g. check the process name too)

Daryn