Linux 中 sysinfo 用來取得系統相關資訊。
int sysinfo(struct sysinfo *info);
回傳值:成功回傳 0,錯誤回傳 -1。
Linux 2.3.16 版本(單位為位元組):
struct sysinfo {
long uptime; /* 開機到現在經過的時間 */
unsigned long loads[3]; /* 1、5、15 分鐘平均負載 */
unsigned long totalram; /* 總可用記憶體大小 */
unsigned long freeram; /* 尚未使用的記憶體大小 */
unsigned long sharedram; /* 共享記憶體大小 */
unsigned long bufferram; /* 緩衝區大小 */
unsigned long totalswap; /* 交換區大小 */
unsigned long freeswap; /* 可用交換區大小 */
unsigned short procs; /* 當前進程數目 */
char _f[22]; /* 64 位元組的補丁結構 */
};
Linux 2.3.23 (i386)、2.3.48(全平台)版本(單位為 mem_unit 位元組):
struct sysinfo {
long uptime;
unsigned long loads[3];
unsigned long totalram;
unsigned long freeram;
unsigned long sharedram;
unsigned long bufferram;
unsigned long totalswap;
unsigned long freeswap;
unsigned short procs;
unsigned long totalhigh; /* 總高記憶體大小 */
unsigned long freehigh; /* 可用高記憶體大小 */
unsigned int mem_unit; /* 以位元組為單位的記憶體大小 */
char _f[20-2*sizeof(long)-sizeof(int)];
};
#include <stdio.h>
#include <unistd.h>
#include <sys/sysinfo.h>
_syscall1(int, sysinfo, struct sysinfo*, info);
int main(int argc, char *agrv[])
{
struct sysinfo s_info;
int error;
error = sysinfo(&s_info);
printf("\n\ncode error=%d\n", error);
printf("Uptime = %ds\nLoad: 1 min %d / 5 min %d / 15 min %d\n"
"RAM: total %d / free %d / shared %d\n"
"Memory in buffers = %d\nSwap: total %d / free %d\n"
"Number of processes = %d\n",
s_info.uptime, s_info.loads[0],
s_info.loads[1], s_info.loads[2],
s_info.totalram, s_info.freeram,
s_info.totalswap, s_info.freeswap,
s_info.procs);
return 0;
}
#include <stdio.h>
#include <sys/sysinfo.h>
struct sysinfo s_info;
long uptime;
int d, h, m, s;
int main()
{
if (0 == sysinfo(&s_info))
{
uptime = s_info.uptime;
d = uptime / (3600 * 24);
h = (uptime / 3600) % 24;
m = (uptime % 3600) / 60;
s = (uptime % 3600) % 60;
printf("d=%d:h=%d:m=%d:s=%d", d, h, m, s);
return 0;
}
return -1;
}
$ gcc -o uptime uptime.c $ ./uptime d=19:h=0:m=4:s=52
實務提醒:不同核心版本、不同 libc 實作下,totalram 等欄位的單位可能不同(新版核心會透過 mem_unit 換算),且部分欄位數值需乘以 mem_unit 才是位元組。另外 _syscall1 巨集在新版 glibc 已不建議使用,直接 #include <sys/sysinfo.h> 呼叫即可。