swapon.c (1550B)
1 /* see LICENSE file for copyright and license details */ 2 3 #include <sys/swap.h> 4 5 #include <mntent.h> 6 #include <stdio.h> 7 #include <stdlib.h> 8 #include <string.h> 9 10 #include "util.h" 11 12 static void 13 usage(void) 14 { 15 eprintf("usage: %s [-dp] -a | device\n", argv0); 16 } 17 18 // ?man swapon: enable swap devices 19 // ?man arguments: -a | device 20 // ?man enable paging and swapping on specified devices 21 int 22 main(int argc, char *argv[]) 23 { 24 int i; 25 int ret = 0; 26 int flags = 0; 27 int all = 0; 28 struct mntent *me; 29 FILE *fp; 30 31 ARGBEGIN 32 { 33 // ?man -a: print or show all entries 34 case 'a': 35 all = 1; 36 break; 37 // ?man -d: specify directory 38 case 'd': 39 flags |= SWAP_FLAG_DISCARD; 40 break; 41 // ?man -p: preserve file attributes 42 case 'p': 43 flags |= SWAP_FLAG_PREFER; 44 break; 45 default: 46 usage(); 47 } 48 ARGEND; 49 50 if ((!all && argc < 1) || (all && argc > 0)) 51 usage(); 52 53 if (all) { 54 fp = setmntent("/etc/fstab", "r"); 55 if (!fp) 56 eprintf("setmntent %s:", "/etc/fstab"); 57 while ((me = getmntent(fp)) != NULL) { 58 if (strcmp(me->mnt_type, MNTTYPE_SWAP) == 0 && (hasmntopt(me, MNTOPT_NOAUTO) == NULL)) { 59 if (swapon(me->mnt_fsname, flags) < 0) { 60 weprintf("swapon %s:", me->mnt_fsname); 61 ret = 1; 62 } 63 } 64 } 65 endmntent(fp); 66 } else { 67 for (i = 0; i < argc; i++) { 68 if (swapon(argv[i], flags) < 0) { 69 weprintf("swapon %s:", argv[i]); 70 ret = 1; 71 } 72 } 73 } 74 return ret; 75 }