busybox/util-linux/swaponoff.c
<<
>>
Prefs
   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 "libbb.h"
  11#include <mntent.h>
  12#include <sys/swap.h>
  13
  14#if ENABLE_FEATURE_SWAPON_PRI
  15struct globals {
  16        int flags;
  17};
  18#define G (*(struct globals*)&bb_common_bufsiz1)
  19#define g_flags (G.flags)
  20#else
  21#define g_flags 0
  22#endif
  23
  24static int swap_enable_disable(char *device)
  25{
  26        int status;
  27        struct stat st;
  28
  29        xstat(device, &st);
  30
  31#if ENABLE_DESKTOP
  32        /* test for holes */
  33        if (S_ISREG(st.st_mode))
  34                if (st.st_blocks * (off_t)512 < st.st_size)
  35                        bb_error_msg("warning: swap file has holes");
  36#endif
  37
  38        if (applet_name[5] == 'n')
  39                status = swapon(device, g_flags);
  40        else
  41                status = swapoff(device);
  42
  43        if (status != 0) {
  44                bb_simple_perror_msg(device);
  45                return 1;
  46        }
  47
  48        return 0;
  49}
  50
  51static int do_em_all(void)
  52{
  53        struct mntent *m;
  54        FILE *f;
  55        int err;
  56
  57        f = setmntent("/etc/fstab", "r");
  58        if (f == NULL)
  59                bb_perror_msg_and_die("/etc/fstab");
  60
  61        err = 0;
  62        while ((m = getmntent(f)) != NULL)
  63                if (strcmp(m->mnt_type, MNTTYPE_SWAP) == 0)
  64                        err += swap_enable_disable(m->mnt_fsname);
  65
  66        endmntent(f);
  67
  68        return err;
  69}
  70
  71int swap_on_off_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  72int swap_on_off_main(int argc UNUSED_PARAM, char **argv)
  73{
  74        int ret;
  75
  76#if !ENABLE_FEATURE_SWAPON_PRI
  77        ret = getopt32(argv, "a");
  78#else
  79        opt_complementary = "p+";
  80        ret = getopt32(argv, (applet_name[5] == 'n') ? "ap:" : "a", &g_flags);
  81
  82        if (ret & 2) { // -p
  83                g_flags = SWAP_FLAG_PREFER |
  84                        ((g_flags & SWAP_FLAG_PRIO_MASK) << SWAP_FLAG_PRIO_SHIFT);
  85                ret &= 1;
  86        }
  87#endif
  88
  89        if (ret /* & 1: not needed */) // -a
  90                return do_em_all();
  91
  92        argv += optind;
  93        if (!*argv)
  94                bb_show_usage();
  95
  96        /* ret = 0; redundant */
  97        do {
  98                ret += swap_enable_disable(*argv);
  99        } while (*++argv);
 100
 101        return ret;
 102}
 103