All pastes #805741 Raw Edit

Untitled

public text v1 · immutable
·published 2007-12-04 16:59 UTC
rendered paste body
using System;
using System.IO;
using System.Collections.Generic;

namespace LinuxProcess 
{

public class ProcStatus
{
	private string _Name;
	private string _Threads;
	private string _Pid;

	public string Name {get {return _Name == null ? string.Empty : _Name; } }
	public string Threads {get {return _Threads == null ? string.Empty : _Threads; } }
	public string Pid {get {return _Pid == null ? string.Empty : _Pid; } }

	public ProcStatus(string status_file)
	{
		if (File.Exists(status_file)) {
			FileStream stream = new FileStream(status_file, FileMode.Open,
					FileAccess.Read);
			StreamReader sr = new StreamReader(stream);
			try {
				while (sr.Peek() > 0)
					ParseLine(sr.ReadLine());
			} finally {
				sr.Close();
				stream.Close();
			}
		}
	}

	private bool ParseLine(string line)
	{
		if (line == null) return false;
		int colon = line.IndexOf(':');

		if (colon > 0 && line.Length > colon) {
			switch(line.Substring(0,colon).ToLower()) {
				case "name":
					_Name = line.Substring(colon + 1).Trim();
					break;
				case "threads":
					_Threads = line.Substring(colon + 1).Trim();
					break;
				case "pid":
					_Pid = line.Substring(colon + 1).Trim();
					break;
			}
		}
		return true;
	}

	public override string ToString()
	{
		return string.Format("{0}: {1}", this.Pid, this.Name);
	}

}

public class ProcList : List<ProcStatus>
{	
	public const string PROC_DIR = "/proc";

	public ProcStatus[] FindByName(string Name)
	{
		if (Name == null) throw new ArgumentNullException("Cannot find by null name");
		List<ProcStatus> list = new List<ProcStatus>();
		Name = Name.Trim();
		foreach (ProcStatus proc_status in this) {
			if (Name.Equals(proc_status.Name)) {
				list.Add(proc_status);
			}
		}
		return list.ToArray();
	}

	public static ProcList AllProcesses()
	{
		List<string> pids = new List<string>();
		ProcList procs = new ProcList();
		for (int i=1; i<10; i++) {
			foreach(string pid_dir in Directory.GetDirectories(PROC_DIR, 
				 string.Format("{0}*", i))) {
				pids.Add(pid_dir);
			}
		}
		
		foreach (string pid in pids) {
			try {
				string status = Path.Combine(pid, "status");
				ProcStatus proc_status = new ProcStatus(status);
				procs.Add(proc_status);
			} catch {}
		}
		
		return procs;
	}
}

}