Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

where does top gets real-time data

Where does top application gets it's data on Linux? I would be interested in real-time CPU load/pid data.(I read allmost all documentation in /proc/pid man page, but the info isn't there).

The pid is a jboss. I need the data lightweight (to be exported easily).

like image 401
Mark Avatar asked Jan 28 '11 10:01

Mark


People also ask

Where does top get its information?

Top gives you a snapshot of a system's situation, e.g., free physical memory, number of running tasks, percentage of CPU time usage of each processes–all in a single view. So it's like using ps, free, and uptime at the same time. Top gets most of its information from several files under the /proc directory.

How does top command work in Linux?

The top (table of processes) command shows a real-time view of running processes in Linux and displays kernel-managed tasks. The command also provides a system information summary that shows resource utilization, including CPU and memory usage. In this tutorial, you will learn to use the top command in Linux.


2 Answers

If in doubt, use strace(1)!

open("/proc/2/stat", O_RDONLY)    = 4
open("/proc/2/statm", O_RDONLY)   = 4
open("/proc/3/stat", O_RDONLY)    = 4
open("/proc/3/statm", O_RDONLY)   = 4
like image 51
adobriyan Avatar answered Nov 28 '22 00:11

adobriyan


As documented in proc(5), in the file /proc/(pid)/stat you have the fields:

utime %lu

Amount of time that this process has been scheduled in user mode, measured in clock ticks (divide by sysconf(_SC_CLK_TCK). This includes guest time, guest_time (time spent running a virtual CPU, see below), so that applications that are not aware of the guest time field do not lose that time from their calculations.

stime %lu

Amount of time that this process has been scheduled in kernel mode, measured in clock ticks (divide by sysconf(_SC_CLK_TCK).

To get CPU usage for a specific process, use those fields. The toplevel process will aggregate CPU usage over all threads; for a per-thread breakdown, you can find the other threads in /proc/(pid)/task.

If you would prefer to be notified when CPU time exceeds some threshold, you can use clock_getcpuclockid to get a handle to its cpu time clock, then timer_create or timerfd to be notified when it hits a specified level. However, note that cross-process cputime timers are an optional feature in the POSIX specification and may not be supported (I've not tested).

like image 45
bdonlan Avatar answered Nov 27 '22 22:11

bdonlan