ab754848ebb89cdfa771b7b0efe885cfc7243f1b
[oweals/busybox.git] / util-linux / swaponoff.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini swapon/swapoff implementation for busybox
4  *
5  * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
6  *
7  * Licensed under the GPL version 2, see the file LICENSE in this tarball.
8  */
9
10 #include "busybox.h"
11 #include <mntent.h>
12 #include <sys/swap.h>
13
14
15 static int swap_enable_disable(char *device)
16 {
17         int status;
18         struct stat st;
19
20         xstat(device, &st);
21
22         /* test for holes */
23         if (S_ISREG(st.st_mode))
24                 if (st.st_blocks * 512 < st.st_size)
25                         bb_error_msg_and_die("swap file has holes");
26
27         if (bb_applet_name[5] == 'n')
28                 status = swapon(device, 0);
29         else
30                 status = swapoff(device);
31
32         if (status != 0) {
33                 bb_perror_msg("%s", device);
34                 return 1;
35         }
36
37         return 0;
38 }
39
40 static int do_em_all(void)
41 {
42         struct mntent *m;
43         FILE *f;
44         int err;
45
46         f = setmntent("/etc/fstab", "r");
47         if (f == NULL)
48                 bb_perror_msg_and_die("/etc/fstab");
49
50         err = 0;
51         while ((m = getmntent(f)) != NULL)
52                 if (strcmp(m->mnt_type, MNTTYPE_SWAP) == 0)
53                         err += swap_enable_disable(m->mnt_fsname);
54
55         endmntent(f);
56
57         return err;
58 }
59
60 #define DO_ALL    0x01
61
62 int swap_on_off_main(int argc, char **argv)
63 {
64         int ret;
65
66         if (argc == 1)
67                 bb_show_usage();
68
69         ret = bb_getopt_ulflags(argc, argv, "a");
70         if (ret & DO_ALL)
71                 return do_em_all();
72
73         ret = 0;
74         while (*++argv)
75                 ret += swap_enable_disable(*argv);
76         return ret;
77 }