args.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. * Copyright (C) 2010 Michael Buesch <m@bues.ch>
  3. *
  4. * This program is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU General Public License
  6. * as published by the Free Software Foundation; either version 2
  7. * of the License, or (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. */
  14. #include "args.h"
  15. #include <stdlib.h>
  16. #include <stdio.h>
  17. #include <getopt.h>
  18. struct cmdline_args cmdargs;
  19. static void usage(FILE *fd, int argc, char **argv)
  20. {
  21. fprintf(fd, "Usage: %s [OPTIONS]\n", argv[0]);
  22. fprintf(fd, "\n");
  23. fprintf(fd, " -B|--background Fork into background\n");
  24. fprintf(fd, " -P|--pidfile PATH Create a PID-file\n");
  25. fprintf(fd, " -l|--loglevel LEVEL Set logging level\n");
  26. fprintf(fd, " 0=error, 1=info, 2=debug, 3=verbose\n");
  27. fprintf(fd, " -L|--logfile PATH Write log to file\n");
  28. fprintf(fd, " -f|--force Force mode\n");
  29. fprintf(fd, "\n");
  30. fprintf(fd, " -h|--help Print this help text\n");
  31. }
  32. int parse_commandline(int argc, char **argv)
  33. {
  34. static struct option long_options[] = {
  35. { "help", no_argument, 0, 'h' },
  36. { "background", no_argument, 0, 'B' },
  37. { "pidfile", required_argument, 0, 'P' },
  38. { "loglevel", required_argument, 0, 'l' },
  39. { "logfile", required_argument, 0, 'L' },
  40. { "force", no_argument, 0, 'f' },
  41. };
  42. int c, idx;
  43. while (1) {
  44. c = getopt_long(argc, argv, "hBP:l:L:f",
  45. long_options, &idx);
  46. if (c == -1)
  47. break;
  48. switch (c) {
  49. case 'h':
  50. usage(stdout, argc, argv);
  51. return 1;
  52. case 'B':
  53. cmdargs.background = 1;
  54. break;
  55. case 'P':
  56. cmdargs.pidfile = optarg;
  57. break;
  58. case 'l':
  59. if (sscanf(optarg, "%d", &cmdargs.loglevel) != 1) {
  60. fprintf(stderr, "Failed to parse --loglevel argument.\n");
  61. return -1;
  62. }
  63. break;
  64. case 'L':
  65. cmdargs.logfile = optarg;
  66. break;
  67. case 'f':
  68. cmdargs.force = 1;
  69. break;
  70. default:
  71. return -1;
  72. }
  73. }
  74. return 0;
  75. }