top command line utility

I'm writing a monitoring application. I'd like to periodically get the information provided by the 'top' command line utility from within my code and write the output of 'top' to a file. Wondering if anyone has already done something like this.
Doing
system("top > someFile");
does not create the file since it depends on the terminal.

What information are you trying to get? What platform and Unix are you using? Running a curses-based app that imposes a measurable amount of load on it's own doesn't sound optimal to me - perhaps there's a way to avoid using 'top -b' to get what you want.

We have a robotics app that is dying. It's usually because a thread is in a tight loop. So I'd like to get cpu usage info. I've been looking at the top code and trying to extract the actual reading of the system info. It's mainly screen handling code. I'm actually building a framework for monitoring real time systems. This app is a small plug in component to that framework.

thanks

This worked for me to get a top snapshot (I'm running bash in Ubuntu 7.10):

top -b -n 1 > ~/Desktop/top.txt

I did a man top to find out that:

-b : Batch mode operation
Starts top in �Batch mode�, which could be useful for sending output from top to other programs or
to a file. In this mode, top will not accept input and runs until the iterations limit you�ve set
with the �-n� command-line option or until killed.

-n : Number of iterations limit as: -n number
Specifies the maximum number of iterations, or frames, top should produce before ending.

I have OpenSuse 10.2 installed and I tried top command like this:

top -b -n 5 -d 3.0 -H > ~/Desktop/top_info.txt

-b - Batch mode
-n - how many itterations
-d - delay of each of each output
-H - out the threads

It works on my PC perfectly.

Curious - my post disappeared!

Well, if you insist on using top, double-check the man page. I found this in mine (shipped with GNU procps-3.2.7-8.1.el5):

Plus, rather than incur an even heavier load by invoking top, you could do as top does to get it's information; in my case it reads /proc/stat to get the CPU counters. Since you didn't reply with your OS, I don't know if this will work for you.

BTW, I'm not sure if you mean RTOS, but if you really need this to be real-time, I'd definitely minimize the impact of monitoring as much as possible.