Rom Lemarchand | 367297c | 2013-06-05 13:25:12 -0700 | [diff] [blame] | 1 | #include <stdio.h> |
| 2 | #include <stdlib.h> |
| 3 | #include <unistd.h> |
| 4 | #include <getopt.h> |
Rom Lemarchand | 367297c | 2013-06-05 13:25:12 -0700 | [diff] [blame] | 5 | #include <sys/swap.h> |
| 6 | |
Elliott Hughes | fd4c6b0 | 2014-07-22 17:20:15 -0700 | [diff] [blame] | 7 | static void usage(char *name) |
Rom Lemarchand | 367297c | 2013-06-05 13:25:12 -0700 | [diff] [blame] | 8 | { |
| 9 | fprintf(stderr, "Usage: %s [-p prio] <filename>\n" |
| 10 | " prio must be between 0 and %d\n", name, SWAP_FLAG_PRIO_MASK); |
| 11 | } |
| 12 | |
Elliott Hughes | fd4c6b0 | 2014-07-22 17:20:15 -0700 | [diff] [blame] | 13 | static int parse_prio(char *prio_str) |
Rom Lemarchand | 367297c | 2013-06-05 13:25:12 -0700 | [diff] [blame] | 14 | { |
| 15 | unsigned long p = strtoul(prio_str, NULL, 10); |
| 16 | |
| 17 | return (p > SWAP_FLAG_PRIO_MASK)? -1 : (int)p; |
| 18 | } |
| 19 | |
| 20 | int swapon_main(int argc, char **argv) |
| 21 | { |
| 22 | int err = 0; |
| 23 | int flags = 0; |
| 24 | int prio; |
| 25 | |
| 26 | opterr = 0; |
| 27 | do { |
| 28 | int c = getopt(argc, argv, "hp:"); |
| 29 | if (c == -1) |
| 30 | break; |
| 31 | |
| 32 | switch (c) { |
| 33 | case 'p': |
| 34 | if (optarg != NULL) |
| 35 | prio = parse_prio(optarg); |
| 36 | else |
| 37 | prio = -1; |
| 38 | |
| 39 | if (prio < 0) { |
| 40 | usage(argv[0]); |
| 41 | return -EINVAL; |
| 42 | } |
| 43 | flags |= SWAP_FLAG_PREFER; |
| 44 | flags |= (prio << SWAP_FLAG_PRIO_SHIFT) & SWAP_FLAG_PRIO_MASK; |
| 45 | break; |
| 46 | case 'h': |
| 47 | usage(argv[0]); |
| 48 | return 0; |
| 49 | case '?': |
| 50 | fprintf(stderr, "unknown option: %c\n", optopt); |
| 51 | return -EINVAL; |
| 52 | } |
| 53 | } while (1); |
| 54 | |
| 55 | if (optind != argc - 1) { |
| 56 | usage(argv[0]); |
| 57 | return -EINVAL; |
| 58 | } |
| 59 | |
| 60 | err = swapon(argv[argc - 1], flags); |
| 61 | if (err) { |
| 62 | fprintf(stderr, "swapon failed for %s\n", argv[argc - 1]); |
| 63 | } |
| 64 | |
| 65 | return err; |
| 66 | } |