如何获得从默认进程冻结进程ID
问题描述:
我想知道是否有可能从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。
这是可能检索?我需要任何外部库吗?
答
Process[] psWerFaultReporter = Process.GetProcessesByName("WerFault");
int werfaultProcessId = -1;
if (psWerFaultReporter.Length > 0)
{
werfaultProcessId = psWerFaultReporter[0].Id;
}
答
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();
}
请解释一下你的答案 – Mazz 2017-04-20 12:14:46
每当一个过程引发了异常,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
命令行类似于: “C:\\ Windows \\ SysWOW64 \\ WerFault.exe -u -p 5012 -s 68“ 因此在这种情况下,5012将是冻结进程的进程ID。使用此ID,您可以使用Process.GetProcessByID函数来搜索特定的进程 – Emphosix 2017-04-20 15:13:04