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