我有一个Win32程序,我可以直接监视另一个Win32进程。
我想找一种方法让监控程序确定受监控的进程是否作为Win32服务运行。
并非所有服务都以SYSTEM身份运行,并且并非所有服务都将services.exe作为直接父级,因此我不认为这些明显的技术足够强大。
要清楚,我正在寻找的是编写函数的方法:
bool isService(HANDLE aProcessHandle){...}
答案 0 :(得分:0)
您可以使用WMI轻松完成此操作。我意识到你没有指定C#,但WMI api在所有平台上都以非常类似的方式提供。
首先我们需要一个形状像Win32_Service
的物体public class Win32_Service
{
public Win32_Service(ManagementBaseObject obj)
{
AcceptPause = (bool)(obj["AcceptPause"] ?? false);
AcceptStop = (bool)(obj["AcceptStop"] ?? false);
Caption = (string)(obj["Caption"] ?? "");
CheckPoint = (UInt32)(obj["CheckPoint"] ?? 0);
CreationClassName = (string)(obj["CreationClassName"] ?? "");
Description = (string)(obj["Description"] ?? "");
DesktopInteract = (bool)(obj["DesktopInteract"] ?? false);
DisplayName = (string)(obj["DisplayName"] ?? "");
ErrorControl = (string)(obj["ErrorControl"] ?? "");
ExitCode = (UInt32)(obj["ExitCode"] ?? 0);
InstallDate = (DateTime)(obj["InstallDate"] ?? DateTime.MinValue);
Name = (string)(obj["Name"] ?? "");
PathName = (string)(obj["PathName"] ?? "");
ProcessId = (UInt32)(obj["ProcessId"] ?? 0);
ServiceSpecificExitCode = (UInt32)(obj["ServiceSpecificExitCode"] ?? 0);
ServiceType = (string)(obj["ServiceType"] ?? "");
Started = (bool)(obj["Started"] ?? false);
StartMode = (string)(obj["StartMode"] ?? "");
StartName = (string)(obj["StartName"] ?? "");
State = (string)(obj["State"] ?? "");
Status = (string)(obj["Status"] ?? "");
SystemCreationClassName = (string)(obj["SystemCreationClassName"] ?? "");
SystemName = (string)(obj["SystemName"] ?? "");
TagId = (UInt32)(obj["TagId"] ?? 0);
WaitHint = (UInt32)(obj["WaitHint"] ?? 0);
}
bool AcceptPause;
bool AcceptStop;
string Caption;
UInt32 CheckPoint;
string CreationClassName;
string Description;
bool DesktopInteract;
string DisplayName;
string ErrorControl;
UInt32 ExitCode;
DateTime InstallDate;
string Name;
string PathName;
UInt32 ProcessId;
UInt32 ServiceSpecificExitCode;
string ServiceType;
bool Started;
string StartMode;
string StartName;
string State;
string Status;
string SystemCreationClassName;
string SystemName;
UInt32 TagId;
UInt32 WaitHint;
};
现在我们查询服务的WMI。在这里,我只是提取所有服务。如果您有更具体的条件,只需修改查询"Select * from Win32_Service"
var services = new System.Collections.Generic.List<Win32_Service>();
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * from Win32_Service"))
{
using (ManagementObjectCollection results = searcher.Get())
{
foreach (ManagementObject obj in results)
{
services.Add(new Win32_Service(obj));
}
}
}
现在您可以使用Linq查询services
。