master xplshn/aruu / cmd / linux / swapon.c
 1/* See LICENSE file for copyright and license details. */
 2
 3
 4#include <sys/swap.h>
 5
 6#include <mntent.h>
 7#include <stdio.h>
 8#include <stdlib.h>
 9#include <string.h>
10
11#include "util.h"
12
13static void
14usage(void)
15{
16	eprintf("usage: %s [-dp] -a | device\n", argv0);
17}
18
19// ?man swapon: enable swap devices
20// ?man arguments: -a | device
21// ?man enable paging and swapping on specified devices
22int
23main(int argc, char *argv[])
24{
25	int i;
26	int ret = 0;
27	int flags = 0;
28	int all = 0;
29	struct mntent *me;
30	FILE *fp;
31
32	ARGBEGIN {
33	// ?man -a: print or show all entries
34	case 'a':
35		all = 1;
36		break;
37	// ?man -d: specify directory
38	case 'd':
39		flags |= SWAP_FLAG_DISCARD;
40		break;
41	// ?man -p: preserve file attributes
42	case 'p':
43		flags |= SWAP_FLAG_PREFER;
44		break;
45	default:
46		usage();
47	} ARGEND;
48
49	if ((!all && argc < 1) || (all && argc > 0))
50		usage();
51
52	if (all) {
53		fp = setmntent("/etc/fstab", "r");
54		if (!fp)
55			eprintf("setmntent %s:", "/etc/fstab");
56		while ((me = getmntent(fp)) != NULL) {
57			if (strcmp(me->mnt_type, MNTTYPE_SWAP) == 0
58			    && (hasmntopt(me, MNTOPT_NOAUTO) == NULL)) {
59				if (swapon(me->mnt_fsname, flags) < 0) {
60					weprintf("swapon %s:", me->mnt_fsname);
61					ret = 1;
62				}
63			}
64		}
65		endmntent(fp);
66	} else {
67		for (i = 0; i < argc; i++) {
68			if (swapon(argv[i], flags) < 0) {
69				weprintf("swapon %s:", argv[i]);
70				ret = 1;
71			}
72		}
73	}
74	return ret;
75}