swaponoff.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. #include <stdio.h>
  10. #include <mntent.h>
  11. #include <dirent.h>
  12. #include <errno.h>
  13. #include <string.h>
  14. #include <stdlib.h>
  15. #include <sys/mount.h>
  16. #include <sys/swap.h>
  17. #include "busybox.h"
  18. static int swap_enable_disable(const char *device)
  19. {
  20. int status;
  21. struct stat st;
  22. xstat(device, &st);
  23. /* test for holes */
  24. if (S_ISREG(st.st_mode))
  25. if (st.st_blocks * 512 < st.st_size)
  26. bb_error_msg_and_die("swap file has holes");
  27. if (bb_applet_name[5] == 'n')
  28. status = swapon(device, 0);
  29. else
  30. status = swapoff(device);
  31. if (status != 0) {
  32. bb_perror_msg("%s", device);
  33. return 1;
  34. }
  35. return 0;
  36. }
  37. static int do_em_all(void)
  38. {
  39. struct mntent *m;
  40. FILE *f;
  41. int err;
  42. f = setmntent("/etc/fstab", "r");
  43. if (f == NULL)
  44. bb_perror_msg_and_die("/etc/fstab");
  45. err = 0;
  46. while ((m = getmntent(f)) != NULL)
  47. if (strcmp(m->mnt_type, MNTTYPE_SWAP) == 0)
  48. err += swap_enable_disable(m->mnt_fsname);
  49. endmntent(f);
  50. return err;
  51. }
  52. #define DO_ALL 0x01
  53. int swap_on_off_main(int argc, char **argv)
  54. {
  55. int ret;
  56. if (argc == 1)
  57. bb_show_usage();
  58. ret = bb_getopt_ulflags(argc, argv, "a");
  59. if (ret & DO_ALL)
  60. return do_em_all();
  61. ret = 0;
  62. while (*++argv)
  63. ret += swap_enable_disable(*argv);
  64. return ret;
  65. }