2014-09-25 109 views
0

我想知道是否有可能從C#中的默認進程獲取相關進程ID。我不想禁用werfault服務,只會得到一個相關(凍結)的進程ID。我寫了這段代碼:如何獲得從默認進程凍結進程ID

Process[] processes = Process.GetProcesses(); 
foreach (Process p in processes) 
{ 
    if (p.ProcessName.ToLower().Contains("werfault")) 
    { 
     //getting related process id? 
    } 
} 

例如:默認的服務報告'programX已停止工作'。我使用上面的代碼來找到werfault進程,然後殺死它並檢索programX pid(我現在不能這麼做)。

我在這裏找到部分答案:How to launch crashing (rarely) application in subprocess但這適用於python。

這是可能檢索?我需要任何外部庫嗎?

回答

0
Process[] psWerFaultReporter = Process.GetProcessesByName("WerFault"); 
    int werfaultProcessId = -1; 
    if (psWerFaultReporter.Length > 0) 
    { 
     werfaultProcessId = psWerFaultReporter[0].Id; 
    } 
0
Process[] processes = Process.GetProcesses(); 
    foreach (Process p in processes) 
    { 
     if (p.ProcessName.ToLower().Contains("werfault")) 
     { 
      // Get the CommandLine string from the werfault.exe 
      string startupParam = GetCommandLine(p); 

      // Get the ProcessID of the frozen Process. 
      // Sure you can optimize this part, but it works in this case :) 
      int pID = int.Parse(startupParam.Split(new string[] { "-p" }, StringSplitOptions.None). 
         Last().Split(new string[] { "-s" }, StringSplitOptions.None).First().Trim()); 

      // Get the frozen Process. 
      Process frozenProcess = Process.GetProcessById(pID); 
     } 
    } 

    /// <summary> 
    /// Returns the CommandLine from a Process. 
    /// </summary> 
    /// <param name="process"></param> 
    /// <returns></returns> 
    private static string GetCommandLine(Process pProcess) 
    { 
     // Create a new CommandLine with the FileName of the given Process. 
     var commandLine = new StringBuilder(pProcess.MainModule.FileName); 
     commandLine.Append(" "); 

     // Now we need to query the CommandLine of the process with ManagementObjectSearcher. 
     using (var searcher = new ManagementObjectSearcher("SELECT CommandLine FROM Win32_Process WHERE ProcessId = " + pProcess.Id)) 
     { 
      // Append the arguments to the CommandLine. 
      foreach (var @object in searcher.Get()) 
      { 
       commandLine.Append(@object["CommandLine"]); 
       commandLine.Append(" "); 
      } 
     } 

     // Return the CommandLine. 
     return commandLine.ToString(); 
    } 
+2

請解釋一下你的答案 – Mazz 2017-04-20 12:14:46

+0

每當一個過程引發了異常,Windows就會啓動werfault.exe,這是「C下找到:\ WINDOWS \ SYSTEM 32 \ WerFault.exe的Windows會自動將PID這個WerFault.exe可以通過使用「GetCommandLine」函數獲得,所以如果你想獲得與WerFault進程相關的凍結應用程序,你首先必須得到CommandLine,它具有已傳遞到該WerFault.exe該命令行包含凍結/崩潰進程的進程ID – Emphosix 2017-04-20 15:08:10

+0

命令行類似於: 「C:\\ Windows \\ SysWOW64 \\ WerFault.exe -u -p 5012 -s 68「 因此在這種情況下,5012將是凍結進程的進程ID。使用此ID,您可以使用Process.GetProcessByID函數來搜索特定的進程 – Emphosix 2017-04-20 15:13:04

相關問題