とんちゃんといっしょ

Cloudに関する技術とか日常とかについて書いたり書かなかったり

C言語で物理メモリ量の取得

C言語で物理メモリ量を取得する方法ががわからなかったので調べてみた。
・・・なかなか情報が見つからずなかったけど無事に目標達成。
結果をまとめておく。

sys/sysinfo.h

 /* Returns information on overall system statistics.  */
 extern int sysinfo (struct sysinfo *__info) __THROW;

linux/kernel.h

 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.. */
 };

sample.c

 #include <stdio.h>
 #include <stdlib.h>
 #include <linux/kernel.h>
 #include <sys/sysinfo.h>
 
 int main(void){
   struct sysinfo *info;
   info = malloc(sizeof(struct sysinfo));
   sysinfo(info);
   fprintf(stderr, "totalmem : %ld kb\n", info->totalram/1024);
   fprintf(stderr, "freemem  : %ld kb\n", info->freeram/1024);
 
   free(info);
   return 0;
 }

出力結果

 totalmem : 32956712 kb
 freemem  : 17050684 kb