main.cpp.tmpl 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include "h.h"
  5. void pexit(int code) {
  6. printf("Exit with code %d.\n", code);
  7. exit(code);
  8. }
  9. typedef struct arg_s {
  10. string cmd;
  11. string confile; // -c
  12. string logfile;
  13. int port; // -p
  14. int daemon; // -d
  15. } arg_t;
  16. arg_t g_arg;
  17. const char* options = "hvc:p:d";
  18. const char* options_descr = "\
  19. Options:\n\
  20. -h Print help\n\
  21. -v Print version\n\
  22. -c confile Configure file\n\
  23. -p port Listen port\n\
  24. -d Daemon\n\
  25. ";
  26. string version() {
  27. return asprintf("%s version %s", g_arg.cmd.c_str(), get_compile_version());
  28. }
  29. string usage() {
  30. return asprintf("Usage: %s [%s]", g_arg.cmd.c_str(), options);
  31. }
  32. void print_help() {
  33. puts(usage().c_str());
  34. puts(options_descr);
  35. puts(version().c_str());
  36. }
  37. bool parse_command_line(int argc, char** argv) {
  38. int opt = -1;
  39. while ((opt = getopt(argc, argv, options)) != -1) {
  40. switch (opt) {
  41. case 'h': {
  42. print_help();
  43. pexit(0);
  44. }
  45. break;
  46. case 'v': {
  47. puts(version().c_str());
  48. pexit(0);
  49. }
  50. break;
  51. case 'c': {
  52. g_arg.confile = optarg;
  53. }
  54. break;
  55. case 'p': {
  56. g_arg.port = atoi(optarg);
  57. }
  58. break;
  59. case 'd': {
  60. g_arg.daemon = 1;
  61. }
  62. break;
  63. default: {
  64. printf("Unrecognized option!");
  65. pexit(-10);
  66. }
  67. break;
  68. }
  69. }
  70. return true;
  71. }
  72. int main(int argc, char** argv) {
  73. string strCmd((const char*)argv[0]);
  74. g_arg.cmd = filename(strCmd);
  75. g_arg.confile = g_arg.cmd + ".conf";
  76. g_arg.logfile = g_arg.cmd + ".log";
  77. g_arg.port = 0;
  78. g_arg.daemon = 0;
  79. hlog_set_file(g_arg.logfile.c_str());
  80. hlog_set_level(LOG_LEVEL_INFO);
  81. hlogi("%s", version().c_str());
  82. if (!parse_command_line(argc, argv)) {
  83. printf("Parse command line error, please use -h to get help.\n");
  84. pexit(-10);
  85. }
  86. IniParser ini;
  87. int iRet = ini.LoadFromFile(g_arg.confile.c_str());
  88. if (iRet != 0) {
  89. printf("Load confile [%s] failed: %d\n", g_arg.confile.c_str(), iRet);
  90. return iRet;
  91. }
  92. if (g_arg.port == 0) {
  93. printf("Please config port!\n");
  94. pexit(-30);
  95. }
  96. #ifdef __unix__
  97. if (g_arg.daemon) {
  98. daemon(1, 1);
  99. }
  100. #endif
  101. pexit(0);
  102. }