view toys/free.c @ 543:60b97ba66a70

Extensive semi-gratuitous refactoring: factor out common code, handle euid!=uid and egid!=gid cases. (Note: test suite requires root access, possibly container support.)
author Rob Landley <>
date Mon, 12 Mar 2012 23:00:28 -0500
parents 878b94b32866
line wrap: on
line source

/* vi: set sw=4 ts=4:
 * free.c - Display amount of free and used memory in the system.
 * Copyright 2012 Elie De Brauwer <>
 * Not in SUSv4.


config FREE
	bool "free"
	default y
	  usage: free [-bkmg]

	  Display the total, free and used amount of physical memory and
	  swap space.

	  -bkmg    Output in bytes (default), KB, MB or GB

#include "toys.h"

static unsigned long long convert(unsigned long d, unsigned int iscale,
				unsigned int oscale)
	return ((unsigned long long)d*iscale)>>oscale;

void free_main(void)
	struct sysinfo info;
	unsigned int iscale = 1;
	unsigned int oscale = 0;

	if (info.mem_unit) iscale = info.mem_unit;
	if (toys.optflags & 1) oscale = 0;
	if (toys.optflags & 2) oscale = 10;
	if (toys.optflags & 4) oscale = 20;
	if (toys.optflags & 8) oscale = 30;

	xprintf("\t\ttotal        used        free      shared     buffers\n");
		convert(info.totalram, iscale, oscale),
		convert(info.totalram-info.freeram, iscale, oscale),
		convert(info.freeram, iscale, oscale),
		convert(info.sharedram, iscale, oscale),
		convert(info.bufferram, iscale, oscale));

	xprintf("-/+ buffers/cache:%15llu%12llu\n",
		convert(info.totalram - info.freeram - info.bufferram, iscale, oscale),
		convert(info.freeram + info.bufferram, iscale, oscale));

		convert(info.totalswap, iscale, oscale),
		convert(info.totalswap - info.freeswap, iscale, oscale),
		convert(info.freeswap, iscale, oscale));