1. 介绍 Linux中,可以用sysinfo来获取系统相关信息。
2. 正文 Linux中,sysinfo是用来获取系统相关信息的结构体。 函数声明和原型:
#include |
int sysinfo(struct sysinfo *info);
返回值:操作成功返回0,错误返回-1; |
2.1 结构体信息: 在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> */ |