summaryrefslogtreecommitdiffabout
path: root/swu.c
blob: 514987991d907d4044f68aac832665a726c989ac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
/* This file is part of swu
 * Copyright (C) 2016 Sergey Poznyakoff
 * 
 * Swu is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3, or (at your option)
 * any later version.
 * 
 * Swu is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with swu.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <unistd.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <inttypes.h>
#include <errno.h>
#include <glob.h>

char *pattern = "/proc/*/status";
int reverse;
int factor;
int show_all;
int show_total;
int sizewidth = 8;
int verbose;
char *progname;

void
err(char const *fmt, ...)
{
	va_list ap;

	fprintf(stderr, "%s: ", progname);
	va_start(ap, fmt);
	vfprintf(stderr, fmt, ap);
	va_end(ap);
	fputc('\n', stderr);
}

struct swu {
	char *name;
	pid_t pid;
	off_t size;
};

struct swu *usage;
size_t nusage;

#define ISWS(c) ((c)==' '||(c)=='\t')
#define SKIPWS(p) do { while (*p && ISWS(*p)) ++p; } while(0)

#define PFX_NAME "Name"
#define PFX_PID  "Pid"
#define PFX_SWAP "VmSwap"

#define SET_NAME 0x1
#define SET_PID  0x2
#define SET_SWAP 0x4
#define SET_ALL (SET_NAME|SET_PID|SET_SWAP)

static char dig[] = "0123456789";

#define READNUM(fun, type)			\
type					        \
fun(char const *s, char **end)			\
{                                               \
	type x = 0;                             \
	char *p;				\
	for (; *s; s++) {			\
		p = strchr(dig, *s);            \
		if (!p)                         \
			break;                  \
		x *= 10;                        \
		x += p - dig;                   \
	}                                       \
	*end = (char*) s;			\
	return x;				\
}

READNUM(readpid, pid_t);
READNUM(readsize, off_t);

int
width(off_t l)
{
	int i;

	for (i = 0; l; i++)
		l>>=1;
	return i*100/332+1;
}

static int
name_match(char const *name, char **argv)
{
	for (; *argv; argv++) {
		if (strcmp(name, *argv) == 0)
			return 1;
	}
	return 0;
}

void
readstat(char const *name, char **argv)
{
	char buf[80];
	FILE *fp;
	struct swu *swp = usage + nusage;
	int f = 0;
	
	fp = fopen(name, "r");
	if (!fp) {
		if (errno != ENOENT)
			err("can't open %s: %s", name, strerror(errno));
		return;
	}
	
	free(swp->name);
	swp->name = NULL;
	
	while ((f & SET_ALL) != SET_ALL && fgets(buf, sizeof(buf), fp)) {
		char *p = buf + strlen(buf);
		if (p[-1] == '\n')
			p[-1] = 0;
		else {
			if (verbose)
				err("%s: line too long: %s", name, buf);
			continue;
		}
		p = strchr(buf, ':');
		if (!p) {
			if (verbose)
				err("%s: unrecognized line: %s", name, buf);
			continue;
		}
		*p++ = 0;
		SKIPWS(p);
		if (strcmp(buf, PFX_NAME) == 0) {
			if (argv[0] && !name_match(p, argv))
				return;
			swp->name = strdup(p);
			if (!swp->name) {
				err("out of memory");
				exit(2);
			}
			f |= SET_NAME;
		} else if (strcmp(buf, PFX_PID) == 0) {
			swp->pid = readpid(p, &p);
			if (*p)
				return;
			f |= SET_PID;
		} else if (strcmp(buf, PFX_SWAP) == 0) {
			swp->size = readsize(p, &p);
			SKIPWS(p);
			if (strcmp(p, "kB") == 0)
				swp->size *= 1024;
			else if (*p)
				return;
			if (swp->size == 0 && !show_all)
				return;
			f |= SET_SWAP;
		}
	}
	fclose(fp);
	if ((f & SET_ALL) == SET_ALL) {
		size_t w = width(swp->size);
		if (w > sizewidth)
			sizewidth = w;
		++nusage;
	}
}

static int
cmp_name(struct swu const *a, struct swu const *b)
{
	return strcmp(a->name, b->name);
}

static int
cmp_pid(struct swu const *a, struct swu const *b)	
{
	if (a->pid < b->pid)
		return -1;
	else
		return 1;
}

static int
cmp_size(struct swu const *a, struct swu const *b)
{
	if (a->size < b->size)
		return -1;
	else if (a->size > b->size)
		return 1;
	return 0;
}

static int (*cmp)(struct swu const *, struct swu const *) = cmp_size;

static int
compare(const void *a, const void *b)
{
	struct swu const *au = a, *bu = b;
	return reverse ? cmp(bu, au) : cmp(au, bu);
}

static int
globerrfunc(const char *epath, int eerrno)
{
	err("%s %s", progname, epath, strerror(eerrno));
	return 1;
}

static void
collect(char **argv)
{
	glob_t g;
	size_t i;
	
	switch (glob(pattern, GLOB_NOSORT, globerrfunc, &g)) {
	case 0:
		break;
	case GLOB_NOSPACE:
		err("out of memory");
		exit(2);
	case GLOB_NOMATCH:
		err("no file matches %s", pattern);
		exit(2);
	default:
		err("globbing error");
		exit(2);
	}

	usage = calloc(g.gl_pathc, sizeof(*usage));
	if (!usage) {
		err("out of memory");
		exit(2);
	}

	for (i = 0; i < g.gl_pathc; i++)
		if (strncmp(g.gl_pathv[i], "/proc/self/", 11))
			readstat(g.gl_pathv[i], argv);
	globfree(&g);
	qsort(usage, nusage, sizeof(usage[0]), compare);
}

void
printsize(off_t size)
{
	static char *suf[] = { "", "K", "M", "G", NULL };
	if (factor) {
		int i;
		unsigned fract = 0;
		for (i = 0; size > factor && suf[i+1]; i++) {
			fract = size % factor;
			size /= factor;
		}
		if (fract)
			printf("% *jd.%01u%s",
			       sizewidth, (intmax_t) size, fract/100, suf[i]);
		else if (i)
			printf("% *jd%s",
			       sizewidth + 2, (intmax_t) size, suf[i]);
		else
			printf("% *jd",  sizewidth + 3, (intmax_t) size);
	} else {
		printf("% *jd",  sizewidth + 3, (intmax_t) size);
	}
}
		

void
output(void)
{
	size_t i;
	off_t total = 0;
	
	for (i = 0; i < nusage; i++) {
		printf("% 8ju", (uintmax_t) usage[i].pid);
		printsize(usage[i].size);
		printf(" %s\n", usage[i].name);
		if (show_total)
			total += usage[i].size;
	}
	if (show_total) {
		printf("%8s", "");
		printsize(total);
		printf(" %s\n", "total");
	}
}

void
help(void)
{
	printf("Usage: %s [OPTION]... [PROGNAME]...\n", progname);
	puts("Summarize swap usage");
	putchar('\n');
	puts("-a, --all             print all entries, including those with zero size");
	puts("--help                produce this help output");
	puts("-h, --human-readable  print sizes in human readable format (e.g., 1K 234M 2G)");
	puts("-H, --si              likewise, but use powers of 1000 not 1024");
	puts("-n, --name            sort output by name");
	puts("-p, --pid             sort output by PID");
	puts("-r, --reverse         reverse sorting order");
	puts("-s, --size            sort output by size (default)");
	puts("-c, -t, --total       produce grand total");
	puts("-v, --verbose         produce additional diagnostics");
	putchar('\n');
	puts("Report bugs to <gray@gnu.org>");
}

#define OPT_HELP 256

struct option opt[] = {
	{ "all",     0, NULL, 'a' },
	{ "help",    0, NULL, OPT_HELP },
	{ "human-readable", 0, NULL, 'h' },
	{ "si",      0, NULL, 'H' },
	{ "name",    0, NULL, 'n' },
	{ "pid",     0, NULL, 'p' },
	{ "reverse", 0, NULL, 'r' },
	{ "size",    0, NULL, 's' },
	{ "total",   0, NULL, 't' },
	{ "verbose", 0, NULL, 'v' },
	{ NULL }
};

int
main(int argc, char **argv)
{
	int c;

	progname = strrchr(argv[0], '/');
	if (progname)
		++progname;
	else
		progname = argv[0];
	while ((c = getopt_long(argc, argv, "acHhnprstv", opt, NULL)) != EOF) {
		switch (c) {
		case 'a':
			show_all = 1;
			break;
		case 'H':
			factor = 1000;
			break;
		case 'h':
			factor = 1024;
			break;
		case 'n':
			cmp = cmp_name;
			break;
		case 'p':
			cmp = cmp_pid;
			break;
		case 'r':
			reverse = 1;
			break;
		case 's':
			cmp = cmp_size;
			break;
		case 'c':
		case 't':
			show_total = 1;
			break;
		case 'v':
			verbose++;
			break;
		case OPT_HELP:
			help();
			exit(0);
		default:
			fprintf(stderr,
				"try '%s --help' for more information.\n",
				progname);
			exit(1);
		}
	}
	if (argc > optind)
		show_all = 1;
	collect(argv + optind);
	output();
	exit(0);
}

Return to:

Send suggestions and report system problems to the System administrator.