开发者

C# WMI Process Differentiation?

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 s开发者_JAVA百科ame name........

....really stumped, help greatly appreciated!


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

  • WMI: Win32_Process.Create method returns [out] uint32 ProcessId
  • .NET: Process.Start method returns a Process object with a Process.Id property

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)


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
     }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜