1、Linux中,sysinfo是用來獲取系統相關信息的結構體。
函數聲明和原型:
int sysinfo(struct sysinfo *info);
返回值:操作成功返回0,錯誤返回-1;
2、結構體信息:
在Linux 2.3.16中,結構體的信息是(單位是字節):
struct sysinfo {
long uptime; /* 啟動到現在經過的時間 */
unsigned long loads[3]; /* 1, 5, and 15 minute load averages*/
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 (all architectures)中,結構體的信息是(單位是mem_unit字節):
struct sysinfo {
long uptime; /* 啟動到現在經過的時間 */
unsigned long loads[3]; /* 1, 5, and 15 minute load averages
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)]; /* libc5的補丁
};
樣例1:
#include
#include /* 包含調用 _syscallX 宏等相關信息*/
#include /* 包含sysinfo結構體信息*/
_syscall1(int, sysinfo, struct sysinfo*, info);
//using namespace std;
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;
}
/*輸出結果:
/home/chenhd/future> ./Sysinfo_1
code error=0
Uptime = 154s
Load: 1 min22976 / 5 min 13888 / 15 min 5408
RAM: total 128307200 / free 55656448 /shared263168000
Memory in buffers = 263168000
Swap:total50/free1073821804
Number of processes = 1073823352
/home/chenhd/future>
*/
樣例2:計算系統啟動時間的方法
#include
#include
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; //由此可見uptime不是秒
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