Patch from Denis Vlasenko to add xstat() and use it.
[platform/upstream/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         xstat(device, &st);
27
28         /* test for holes */
29         if (S_ISREG(st.st_mode))
30                 if (st.st_blocks * 512 < st.st_size)
31                         bb_error_msg_and_die("swap file has holes");
32
33         if (bb_applet_name[5] == 'n')
34                 status = swapon(device, 0);
35         else
36                 status = swapoff(device);
37
38         if (status != 0) {
39                 bb_perror_msg("%s", device);
40                 return 1;
41         }
42
43         return 0;
44 }
45
46 static int do_em_all(void)
47 {
48         struct mntent *m;
49         FILE *f;
50         int err;
51
52         f = setmntent("/etc/fstab", "r");
53         if (f == NULL)
54                 bb_perror_msg_and_die("/etc/fstab");
55
56         err = 0;
57         while ((m = getmntent(f)) != NULL)
58                 if (strcmp(m->mnt_type, MNTTYPE_SWAP) == 0)
59                         err += swap_enable_disable(m->mnt_fsname);
60
61         endmntent(f);
62
63         return err;
64 }
65
66 #define DO_ALL    0x01
67
68 int swap_on_off_main(int argc, char **argv)
69 {
70         int ret;
71
72         if (argc == 1)
73                 bb_show_usage();
74
75         ret = bb_getopt_ulflags(argc, argv, "a");
76         if (ret & DO_ALL)
77                 return do_em_all();
78
79         ret = 0;
80         while (*++argv)
81                 ret += swap_enable_disable(*argv);
82         return ret;
83 }