Linux 下监控程序升级版

Linux 下监控程序升级版

#include<stdio.h>
#include<unistd.h>

class VMSTAT
{
public:
	double stat[20];
	/*
	 *       Proc
	 *
	 * 0:r: The number of processes waiting for run time.
	 * 1:b: The number of processes in uninterruptible sleep.
	 *
	 *       Memory
	 *
	 * 2:swpd: the amount of virtual memory used.
	 * 3:free: the amount of idle memory.
	 * 4:buff: the amount of memory used as buffers.
	 * 5:cache: the amount of memory used as cache.
	 *
	 *       Swap
	 *
	 * 6:si: Amount of memory swapped in from disk (/s).
	 * 7:Amount of memory swapped to disk (/s).
	 *
	 *       IO
	 *
	 * 8:bi: Blocks received from a block device (blocks/s).
	 * 9:bo: Blocks sent to a block device (blocks/s).
	 *
	 *       System
	 *
	 * 10:in: The number of interrupts per second, including the clock.
	 * 11:cs: The number of context switches per second.
	 *
	 *       CPU
	 *
	 * 12:us: Time spent running non-kernel code. (user time, including nice time)
	 * 13:sy: Time spent running kernel code. (system time)
	 * 14:id: Time spent idle. Prior to Linux 2.5.41, this includes IO-wait time.
	 * 15:wa: Time spent waiting for IO. Prior to Linux 2.5.41, included in idle.
	 * 16:st: Time stolen from a virtual machine. Prior to Linux 2.6.11, unknown.
	 *
	 *       Add
	 *
	 * 17:Total Memory
	 * 18:Used Memory
	 * 19:CPU Usage
	 */

	void update()
	{

		//init array
		FILE *file = popen("vmstat", "r");
		char buf[300];
		fgets(buf, 300, file);
		fgets(buf, 300, file);
		fgets(buf, 300, file);

		int index = 0;
		for (int i = 0; i < 300; i++)
		{
			while (buf[i] < '0' || buf[i] > '9')
				i++;
			int tmp = 0;
			while (buf[i] >= '0' && buf[i] <= '9')
			{
				tmp = tmp * 10 + (buf[i] - '0');
				i++;
			}
			stat[index++] = tmp * 1.0;
			if (index == 17)
				break;
		}
		pclose(file);

		//total memory
		file = popen("cat /proc/meminfo", "r");
		double total = 0;
		fgets(buf, 300, file);
		char str[7];
		for (int i = 17; i < 24; i++)
			str[i - 17] = buf[i];

		for (int i = 0; i < 7; i++)
		{
			total = total * 10 + (str[i] == ' ' ? 0 : (str[i] - '0'));
		}

		//calculate all
		stat[17] = total;
		stat[18] = total - stat[3];
		stat[19] = 100 - stat[14];
		pclose(file);

	}

};

int main()
{

	VMSTAT s;
	while (1)
	{
		s.update();
		printf("Total: %d MB  Aviliable: %d MB  Used: %d MB  CPU: %d %\n",
				int(s.stat[17] / 1000), int(s.stat[3] / 1000),
				int(s.stat[18] / 1000), int(s.stat[19]));
		sleep(1);
	}

	return 0;
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注