博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[转载]如何对系统中的某个进程进行监控
阅读量:2448 次
发布时间:2019-05-10

本文共 6152 字,大约阅读时间需要 20 分钟。

最近看到一篇文章,就是如何对系统某个进程进行监控,并且当这个进程触发某些事件的时候,能进行相应。而且发现有人问这方面的问题,我就大致在其原有的基础进行如下的修改。

首先说明的一点,方法是基于WMI的。以下是我扩展类的代码说明:

//------------------------ProcessInfo Class------------------------------------

//-----------------------------------------------------------------------------

//---File:clsProcessInfo.cs

//---Description:This class demonstrates the use of WMI.

// It provides a static method to query the list of running processes.

// And it provides two delegated events binding specific application.

//---Author:Knight

//---Date:Mar.21, 2006

//-----------------------------------------------------------------------------

//----------------------{ ProcessInfo Class }----------------------------------

using System;

using System.Data;

using System.Management;

using System.Diagnostics;

namespace WinProcess

{

///

/// ProcessInfo class.

///

public class ProcessInfo

{

// defenition of the delegates

public delegate void StartedEventHandler(object sender, EventArgs e);

public delegate void TerminatedEventHandler(object sender, EventArgs e);

// events to subscribe

public StartedEventHandler Started = null;

public TerminatedEventHandler Terminated = null;

// WMI event watcher

private ManagementEventWatcher watcher;

///

/// Construction that binds specific application with event declared

///

///

///

public ProcessInfo( string appName)

{

// querry every 2 seconds

string pol = "2";

string queryString =

"SELECT *" +

" FROM __InstanceOperationEvent " +

"WITHIN " + pol +

" WHERE TargetInstance ISA 'Win32_Process' " +

" AND TargetInstance.Name = '" + appName + "'";

string scope = @"\127.0.0.1 ootCIMV2";

// create the watcher and start to listen

watcher = new ManagementEventWatcher(scope, queryString);

watcher.EventArrived += new EventArrivedEventHandler(this.OnEventArrived);

watcher.Start();

}

///

/// Destruction function

///

public void Dispose()

{

watcher.Stop();

watcher.Dispose();

}

///

/// Get all processes that running in local machine

///

///

public static DataTable RunningProcesses( )

{

// The second way of constructing a query

string queryString =

"SELECT Name, ProcessId, Caption, ExecutablePath" +

" FROM Win32_Process";

SelectQuery query = new SelectQuery(queryString);

ManagementScope scope = new ManagementScope( @"\127.0.0.1 ootCIMV2" );

ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);

ManagementObjectCollection processes = searcher.Get();

DataTable result = new DataTable();

result.Columns.Add("Name", Type.GetType("System.String"));

result.Columns.Add("ProcessId", Type.GetType("System.Int32"));

result.Columns.Add("Caption", Type.GetType("System.String"));

result.Columns.Add("Path", Type.GetType("System.String"));

foreach(ManagementObject mo in processes)

{

DataRow row = result.NewRow();

row["Name"] = mo["Name"].ToString();

row["ProcessId"] = Convert.ToInt32(mo["ProcessId"]);

if (mo["Caption"]!= null)

row["Caption"] = mo["Caption"].ToString();

if (mo["ExecutablePath"]!= null)

row["Path"] = mo["ExecutablePath"].ToString();

result.Rows.Add( row );

}

return result;

}

///

/// Get all processes that running in specific server

///

///

///

///

///

public static DataTable RunningProcesses(

string sServerName,

string sUserName,

string sPassword )

{

// The second way of constructing a query

string queryString =

"SELECT Name, ProcessId, Caption, ExecutablePath" +

" FROM Win32_Process";

SelectQuery query = new SelectQuery(queryString);

//Set connection parameters

ConnectionOptions options = new ConnectionOptions();

options.Username = sUserName;

options.Password = sPassword;

//Create management scope

ManagementScope scope = new ManagementScope(

string.Format( @"\{0} ootCIMV2", sServerName ),

options );

//To connect

try

{

scope.Connect();

}

catch( Exception err )

{

Debug.WriteLine( err.Message );

return null;

}

catch

{

return null;

}

ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);

ManagementObjectCollection processes = searcher.Get();

DataTable result = new DataTable();

result.Columns.Add("Name", Type.GetType("System.String"));

result.Columns.Add("ProcessId", Type.GetType("System.Int32"));

result.Columns.Add("Caption", Type.GetType("System.String"));

result.Columns.Add("Path", Type.GetType("System.String"));

foreach(ManagementObject mo in processes)

{

DataRow row = result.NewRow();

row["Name"] = mo["Name"].ToString();

row["ProcessId"] = Convert.ToInt32(mo["ProcessId"]);

if (mo["Caption"]!= null)

row["Caption"] = mo["Caption"].ToString();

if (mo["ExecutablePath"]!= null)

row["Path"] = mo["ExecutablePath"].ToString();

result.Rows.Add( row );

}

return result;

}

///

/// Event handle function

///

///

///

private void OnEventArrived(object sender, System.Management.EventArrivedEventArgs e)

{

try

{

string eventName = e.NewEvent.ClassPath.ClassName;

Debug.WriteLine( eventName );

if (eventName.CompareTo("__InstanceCreationEvent")==0)

{

// Started

if (Started!=null)

Started(this, e);

}

else if (eventName.CompareTo("__InstanceDeletionEvent")==0)

{

// Terminated

if (Terminated!=null)

Terminated(this, e);

}

}

catch (Exception ex)

{

Debug.WriteLine(ex.Message);

}

}

}

}

大致类的说明如下:

1. 两个静态方法,是获得系统中所有进程(一个是获得本地;另一个是获得某个指定的服务器);

2. OnEventArrived,事件响应函数,当根据事件类型来进行传递;

类的使用大致如下:

1. 获得本地系统中所有进程:

using WinProcess;

DataTable dt = ProcessInfo.RunningProcesses( );

dataGrid1.DataSource = dt;

2. 获得某个指定系统中所有进程:

using WinProcess;

DataTable dt = ProcessInfo.RunningProcesses( Server, UserName, Psw );

dataGrid1.DataSource = dt;

3. 监控某个程序并(以下是监控NotePad程序):

using WinProcess;

private ProcessInfo notePad;

//In your form load event

notePad = new ProcessInfo("notepad.exe" );

notePad.Started += new ProcessInfo.StartedEventHandler(this.NotepadStarted);

notePad.Terminated += new ProcessInfo.TerminatedEventHandler (this.NotepadTerminated);

//Define your event handle

private void NotepadStarted(object sender, EventArgs e)

{

//Process start event

}

private void NotepadTerminated(object sender, EventArgs e)

{

//Process terminate event

}

本来,想修改构造函数,使之能适应捕获到远程系统某个程序的事件,但是很不幸的是,捕获到的信息只是错误信息,其原因就是事件无法通过RPC获得,所以不得不放弃。

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/374079/viewspace-130588/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/374079/viewspace-130588/

你可能感兴趣的文章
如何在Python中将纪元时间戳转换为人类可读的日期格式?
查看>>
gdb32和gdb_GDB备忘单
查看>>
xen nfs挂载_如何在没有Xen的Linux上附加和挂载Xen DomU的磁盘分区?
查看>>
caliber读书软件_如何在无头服务器上运行gitbook(使Caliber在无头服务器上运行)?...
查看>>
Windows 7 64位无法在状态码为0xc0000225的VirtualBox / Linux上安装
查看>>
n字节对齐 代码_大但正确对齐和优化的代码比每指令/操作码打包的字节少的代码快...
查看>>
火狐 旧版sync同步服务_如何设置Firefox Sync?
查看>>
python的smiley_SmIley面对iPhone
查看>>
vim搜索 不区分大小写_Vim:不区分大小写的搜索
查看>>
电脑备份iphone_如何在Linux上备份iPhone?
查看>>
latex在编译公式_如何在Linux上编译Latex
查看>>
同步主目录
查看>>
hadoop单机映射_如何在命令行中设置Hadoop的映射器和缩减器的数量?
查看>>
svg转换为png_如何在Linux中将svg转换为png?
查看>>
virtualbox 缩放_如何相当VirtualBox缩放模式?
查看>>
node.js退出命令_如何在Node.js中退出程序?
查看>>
wordpress 域名_WordPress MU:更改域名
查看>>
更改linux mtu_更改MTU以使Linux上的WiFi更快
查看>>
ubuntu gui_Ubuntu的GUI响应非常慢
查看>>
opam 命令行_添加Jane Street Opam存储库
查看>>