The top command calculates CPU usage using data in the proc file system. The actual file containing CPU usage data may vary from one platform to another. For example, on Linux it is located in /proc/<pid>/stat , and for Solaris it is located in /proc/<pid>/psinfo . CPU usage is calculated as the difference in cumulative processor time for a process divided by the amount of time measured between updates.
For Linux, you can check out the procps source, which includes ps , top and other process tools from http://procps.sourceforge.net . The readproc.c file contains functions for retrieving data.
For Solaris, you can check the libproc source from https://hg.java.net/hg/solaris~on-src/file/tip/usr/src/lib/libproc . The prog_get_info.c file contains functions for retrieving data and storing it in psinfo_t struct.
For Linux, Solaris, and others, you can check out the Unix Top source from http://sourceforge.net/projects/unixtop . Platform-specific source files in the machine directory contain functions for retrieving data.
Update
Another option (Solaris only) for getting the CPU time for a process can be passed to the PIOCPSINFO or PIOCSTATUS variant ioctl() . The PIOCPSINFO option returns information about different processes in prpsinfo_t struct. The PIOCSTATUS option returns status information for the process in prstatus_t struct.
Adapted from the sample code at http://getthegood.com/TechNotes/Papers/ProcStatistics.html :
int main(int argc, char* argv[]) { int fd; prpsinfo_t info; prstatus_t status; char procbuf[50]; sprintf(procbuf, "/proc/%d", getpid()); fd = open(procbuf, O_RDONLY); ioctl(fd, PIOCPSINFO, &info); printf("Process user+sys time = %ld sec %ld nsec\n" "Reaped children user+sys time = %ld sec %ld nsec\n", info.pr_time.tv_sec, info.pr_time.tv_nsec, info.pr_ctime.tv_sec, info.pr_ctime.tv_nsec); ioctl(fd, PIOCSTATUS, &status); printf("Process user+sys time = %ld sec %ld nsec\n" "Sum of children user+sys time = %ld sec %ld nsec\n", status.pr_utime.tv_sec+status.pr_stime.tv_sec, status.pr_utime.tv_nsec+status.pr_stime.tv_nsec, status.pr_cutime.tv_sec+status.pr_cstime.tv_sec, status.pr_cutime.tv_nsec+status.pr_cstime.tv_nsec); close(fd); exit(0); }
Note. This code is untested and omits error checking for simplicity.