master xplshn/aruu / cmd / linux / lsmod.c
 1
 2#include <stdio.h>
 3#include <stdlib.h>
 4#include <string.h>
 5
 6#include "text.h"
 7#include "util.h"
 8
 9static void parse_modline(char *buf, char **name, char **size,
10			  char **refcount, char **users);
11
12static void
13usage(void)
14{
15	eprintf("usage: %s\n", argv0);
16}
17
18// ?man lsmod: show the status of modules in the Linux kernel
19// ?man lsmod formats and displays /proc/modules, showing currently loaded modules
20int
21main(int argc, char *argv[])
22{
23	const char *modfile = "/proc/modules";
24	FILE *fp;
25	char *buf = NULL;
26	char *name, *size, *refcount, *users;
27	size_t bufsize = 0;
28	size_t len;
29
30	ARGBEGIN {
31	default:
32		usage();
33	} ARGEND;
34
35	if (argc > 0)
36		usage();
37
38	fp = fopen(modfile, "r");
39	if (!fp)
40		eprintf("fopen %s:", modfile);
41
42	printf("%-23s Size  Used by\n", "Module");
43
44	while (agetline(&buf, &bufsize, fp) != -1) {
45		parse_modline(buf, &name, &size, &refcount, &users);
46		if (!name || !size || !refcount || !users)
47			eprintf("invalid format: %s\n", modfile);
48		len = strlen(users) - 1;
49		if (users[len] == ',' || users[len] == '-')
50			users[len] = '\0';
51		printf("%-20s%8s%3s %s\n", name, size, refcount,
52		       users);
53	}
54	if (ferror(fp))
55		eprintf("%s: read error:", modfile);
56	free(buf);
57	fclose(fp);
58	return 0;
59}
60
61static void
62parse_modline(char *buf, char **name, char **size,
63	      char **refcount, char **users)
64{
65	*name = strtok(buf, " ");
66	*size = strtok(NULL, " ");
67	*refcount = strtok(NULL, " ");
68	*users = strtok(NULL, " ");
69}