swaponoff.c 1.9 KB

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