This project is read-only.

get linux cpu usage top

Jan 17, 2012 at 5:29 PM

Hello everyone,

I am trying to monitor the cpu usage on a few different systems, and am trying to execute the 'top -n1' command.

I am receiving: this.OutputStream.ReadTimeout' threw an exception of type 'System.InvalidOperationException' and no results

Any suggestions or a better way to accomplish this?

				var cmd = ssh.CreateCommand ( "top -n1" );
				var asynch = cmd.BeginExecute(delegate(IAsyncResult ar)
				{
					Console.WriteLine("Finished.");
				}, null);

				var reader = new StreamReader(cmd.OutputStream);

				while (!asynch.IsCompleted)
				{
					var result = reader.ReadToEnd();
					if (string.IsNullOrEmpty(result))
						continue;
					Console.Write(result);
				}
				cmd.EndExecute(asynch);

Jan 17, 2012 at 6:50 PM

I did something similar by periodically executing a ps command.  You can format the result with the -o flag.  For example, if you are interested in the PID and CPU usage, try something like this:

var cmd = ssh.CreateCommand("ps ef -o pid,pcpu");
string result = cmd.Execute();
//parse result...
After execute returns, each line of result will contain a pid followed by the cpu usage.  You can throw out the first line since it should be nothing but column headers.  For other output fields, refer to the man pages for ps - the valid format specifiers should be listed there.

Jan 17, 2012 at 8:10 PM
Edited Jan 17, 2012 at 8:44 PM

Thats a great idea! i started messing with the ps aux ( ps aux | sort -n -k 3 -r | head ) and all that but i think the formatting command will work better.

Thanks again