January 19, 2007
Hi there,
  I'm working on a function that determines what percentage of basic resources (CPU, memory, etc) the calling application is using (on *NIX, but eventually for windows as well). So far the best solution I've come up with is to use the ps utility, but I'm not sure what method I should use to retrieve the output. I could have it output to file or pipe the output somewhere, but all of this seems extremely awkward for such a simple task. Are there some libraries out there that could assist me with this, or is there at least a simple way to retrieve the output from  ps?

 Thank you very much for your time,
  ~Morgan McDermott
January 28, 2007
Mmcdermo wrote:
> Hi there,
>   I'm working on a function that determines what percentage of basic resources (CPU, memory, etc) the calling application is using (on *NIX, but eventually for windows as well). So far the best solution I've come up with is to use the ps utility, but I'm not sure what method I should use to retrieve the output. I could have it output to file or pipe the output somewhere, but all of this seems extremely awkward for such a simple task. Are there some libraries out there that could assist me with this, or is there at least a simple way to retrieve the output from  ps?
> 
>  Thank you very much for your time,
>   ~Morgan McDermott

You can run ps via fork / exec and parse the output, the way a shell script would, but a less messy solution would be to determine how ps works and do the same thing.  You can tell exactly what ps does using the "strace" command.

But for recent versions of Linux I think utilities like 'top' and 'ps' use the /proc filesystem.  For example, if you want to know the virtual memory size of a process, you can read /proc/12345/status, and look for "VmSize".  That is for PID 12345, you can also use "/proc/self/status" for the current process -- it returns the data for which ever process is reading the file (the kernel knows all).

This can be parsed, but there is a bad interaction between std.file and a lot of the files in /proc because Linux reports the filesize as zero even if it is readable --- it's not really 'data', when you read the file the linux kernel just does a "printf" into a buffer and returns this to your process.  So I think you need to use Stream instead of std.file for these pseudo-files.

The other trick is figuring out what all these numbers mean; I suggest Google for this, since I imagine its documented ... somewhere.

Kevin