sysinfo 系统调用

在分析luci时,看到 usr/lib/luci/sys.lua 里调用 nixio.sysinfo()。这是一个c调用lua的用例。在nixio的代码process.c里导出了给lua调用的接口。在其中看到nixio.sysinfo()的实现是调用linux的sysinfo()系统调用。

       #include <sys/sysinfo.h>

       int sysinfo(struct sysinfo *info)

成功返回0, 失败返回-1,同时errno被赋值。 struct sysinfo 的结构是:

           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 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 to 64 bytes */
           };

系统负载平均值,其基数是1 << SI_LOAD_SHIFT, SI_LOAD_SHIFT是个偏移值。 函数使用很简单,见下例:


#include <stdio.h>
#include <sys/sysinfo.h>

int main(void)
{
	struct sysinfo info;

	if (sysinfo(&info) < 0) {
		perror("sysinfo failed");
		return -1;
	}

	printf("uptime    %ld
", info.uptime   );
	printf("loads %.2f, %.2f, %.2f
",
	       (double)info.loads[0] / (1 << SI_LOAD_SHIFT),
	       (double)info.loads[1] / (1 << SI_LOAD_SHIFT),
	       (double)info.loads[2] / (1 << SI_LOAD_SHIFT));
	printf("totalram  %ld
", info.totalram );
	printf("freeram   %ld
", info.freeram  );
	printf("sharedram %ld
", info.sharedram);
	printf("bufferram %ld
", info.bufferram);
	printf("totalswap %ld
", info.totalswap);
	printf("freeswap  %ld
", info.freeswap );
	printf("procs     %d
",  info.procs    );
	printf("totalhigh %ld
", info.totalhigh);
	printf("freehigh  %ld
", info.freehigh );
	printf("mem_unit  %d
",  info.mem_unit );

	return 0;
}
原文地址:https://www.cnblogs.com/sammei/p/3955461.html