Indice

Usare la funzione sysinfo()

Autore: Fabio Di Matteo
Ultima revisione: 01/04/2008

La funzione sysinfo() fornisce un modo semplice di ottenere statistiche globali di sistema.

ecco come usarla:

#include <sys/sysinfo.h> 
 
int main () 
{
  /* Costanti per la conversione. */ 
  const long minute = 60; 
  const long hour = minute * 60; 
  const long day = hour * 24; 
  const double megabyte = 1024 * 1024; 
  /* Riempo le statistiche */ 
  struct sysinfo si; 
  sysinfo (&si); 
  /* Stampo i valori. */ 
  printf ("\nPc acceso da : %ld days, %ld:%02ld:%02ld\n", 
          si.uptime / day, (si.uptime % day) / hour, 
          (si.uptime % hour) / minute, si.uptime % minute); 
  printf ("RAM totale     : %5.1f MB\n", si.totalram / megabyte); 
  printf ("RAM libera      : %5.1f MB\n", si.freeram / megabyte); 
  printf ("Numero di processi : %d\n", si.procs); 
  return 0; 
} 

Compilazione

Niente di particolare:

gcc main.c -o main

La struct ''sysinfo''

La struttura sysinfo è definita nel file <linux/kernel.h> (di solito /usr/include/linux/kernel.h)

#ifndef _LINUX_KERNEL_H
#define _LINUX_KERNEL_H
 
/*
 * 'kernel.h' contains some often-used function prototypes etc
 */
 
 
#define SI_LOAD_SHIFT	16
struct sysinfo {
	long uptime;			/* Seconds since boot */
	unsigned long loads[3];		/* 1, 5, and 15 minute load averages */
	unsigned long totalram;		/* Total usable main memory size */
	unsigned long freeram;		/* Available memory size */
	unsigned long sharedram;	/* Amount of shared memory */
	unsigned long bufferram;	/* Memory used by buffers */
	unsigned long totalswap;	/* Total swap space size */
	unsigned long freeswap;		/* swap space still available */
	unsigned short procs;		/* Number of current processes */
	unsigned short pad;		/* explicit padding for m68k */
	unsigned long totalhigh;	/* Total high memory size */
	unsigned long freehigh;		/* Available high memory size */
	unsigned int mem_unit;		/* Memory unit size in bytes */
	char _f[20-2*sizeof(long)-sizeof(int)];	/* Padding: libc5 uses this.. */
};
 
/* Force a compilation error if condition is true */
#define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))
 
/* Force a compilation error if condition is true, but also produce a
   result (of value 0 and type size_t), so the expression can be used
   e.g. in a structure initializer (or where-ever else comma expressions
   aren't permitted). */
#define BUILD_BUG_ON_ZERO(e) (sizeof(char[1 - 2 * !!(e)]) - 1)
 
/* Trap pasters of __FUNCTION__ at compile-time */
#define __FUNCTION__ (__func__)
 
/* This helps us to avoid #ifdef CONFIG_NUMA */
#ifdef CONFIG_NUMA
#define NUMA_BUILD 1
#else
#define NUMA_BUILD 0
#endif
 
#endif