8.14 sysinfo: Obtaining System Statistics

The sysinfo system call fills a structure with system statistics. Its only argument is a pointer to a struct sysinfo. Some of the more interesting fields of struct sysinfo that are filled include these:

·         uptime— Time elapsed since the system booted, in seconds

·         totalram— Total available physical RAM

·         freeram— Free physical RAM

·         procs— Number of processes on the system

See the sysinfo man page for a full description of structsysinfo. Include <linux/kernel.h>, <linux/sys.h>, and <sys/sysinfo.h> if you use sysinfo.

The program in Listing 8.12 prints some statistics about the current system.

Listing 8.12 (sysinfo.c) Print System Statistics
#include <linux/kernel.h> 
#include <linux/sys.h> 
#include <stdio.h> 
#include <sys/sysinfo.h> 
int main () 
  /* Conversion constants. */ 
  const long minute = 60; 
  const long hour = minute * 60; 
  const long day = hour * 24; 
  const double megabyte = 1024 * 1024; 
  /* Obtain system statistics. */ 
  struct sysinfo si; 
  sysinfo (&si); 
  /* Summarize interesting values. */ 
  printf ("system uptime : %ld days, %ld:%02ld:%02ld\n", 
          si.uptime / day, (si.uptime % day) / hour, 
          (si.uptime % hour) / minute, si.uptime % minute); 
  printf ("total RAM     : %5.1f MB\n", si.totalram / megabyte); 
  printf ("free RAM      : %5.1f MB\n", si.freeram / megabyte); 
  printf ("process count : %d\n", si.procs); 
  return 0;