The major:minor read from dev ends with \n, need to trim that.
[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 v2, see the file LICENSE in this tarball.
8  */
9
10 #include <stdio.h>
11 #include <mntent.h>
12 #include <dirent.h>
13 #include <errno.h>
14 #include <string.h>
15 #include <stdlib.h>
16 #include <sys/mount.h>
17 #include <sys/swap.h>
18
19 #include "busybox.h"
20
21 static int swap_enable_disable(const char *device)
22 {
23         int status;
24         struct stat st;
25
26         if (stat(device, &st) < 0)
27                 bb_perror_msg_and_die("cannot stat %s", device);
28
29         /* test for holes */
30         if (S_ISREG(st.st_mode))
31                 if (st.st_blocks * 512 < st.st_size)
32                         bb_error_msg_and_die("swap file has holes");
33
34         if (bb_applet_name[5] == 'n')
35                 status = swapon(device, 0);
36         else
37                 status = swapoff(device);
38
39         if (status != 0) {
40                 bb_perror_msg("%s", device);
41                 return 1;
42         }
43
44         return 0;
45 }
46
47 static int do_em_all(void)
48 {
49         struct mntent *m;
50         FILE *f;
51         int err;
52
53         f = setmntent("/etc/fstab", "r");
54         if (f == NULL)
55                 bb_perror_msg_and_die("/etc/fstab");
56
57         err = 0;
58         while ((m = getmntent(f)) != NULL)
59                 if (strcmp(m->mnt_type, MNTTYPE_SWAP) == 0)
60                         err += swap_enable_disable(m->mnt_fsname);
61
62         endmntent(f);
63
64         return err;
65 }
66
67 #define DO_ALL    0x01
68
69 extern int swap_on_off_main(int argc, char **argv)
70 {
71         int ret;
72
73         if (argc == 1)
74                 bb_show_usage();
75
76         ret = bb_getopt_ulflags(argc, argv, "a");
77         if (ret & DO_ALL)
78                 return do_em_all();
79
80         ret = 0;
81         while (*++argv)
82                 ret += swap_enable_disable(*argv);
83         return ret;
84 }