rpc.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <getopt.h>
  5. #include <signal.h>
  6. #include <syslog.h>
  7. #include <sys/stat.h>
  8. #include "include/run_server.h"
  9. #include "include/run_client.h"
  10. #define PORT 4457
  11. static struct option program_options[] =
  12. {
  13. {"help", no_argument, 0, 'h'},
  14. {"server", no_argument, 0, 's'},
  15. {"reboot", required_argument, 0, 'r'},
  16. {"poweroff", required_argument, 0, 'p'}
  17. };
  18. void show_help(const char* exe_name)
  19. {
  20. printf("Usage: %s [OPTION]... [ARG]...\n", exe_name);
  21. printf("\tOption\t\t\tDescription\n");
  22. printf("\t---------------------------------------------\n");
  23. printf("\t--help\t\t\tdisplay help and exit\n");
  24. printf("\t--server\t\trun server mode\n");
  25. printf("\t--reboot [addr]\t\treboot the target\n");
  26. printf("\t--poweroff [addr]\tshutdown the target\n");
  27. }
  28. void terminate()
  29. {
  30. exit(EXIT_SUCCESS);
  31. }
  32. void daemonize_process()
  33. {
  34. pid_t pid = fork();
  35. if (pid < 0)
  36. exit(EXIT_FAILURE);
  37. if (pid > 0)
  38. exit(EXIT_SUCCESS);
  39. if (setsid() < 0)
  40. exit(EXIT_FAILURE);
  41. signal(SIGTERM, terminate);
  42. signal(SIGHUP, SIG_IGN);
  43. pid = fork();
  44. if (pid < 0)
  45. exit(EXIT_FAILURE);
  46. if (pid > 0)
  47. exit(EXIT_SUCCESS);
  48. umask(0);
  49. chdir("/");
  50. }
  51. int main(int argc, char** argv)
  52. {
  53. if (argc < 2)
  54. {
  55. show_help(argv[0]);
  56. exit(EXIT_SUCCESS);
  57. }
  58. int curr_option = 0;
  59. int error_code = 0;
  60. while (1)
  61. {
  62. curr_option = getopt_long_only(argc, argv, "hs:rp", program_options, NULL);
  63. if (curr_option == -1)
  64. break;
  65. switch (curr_option)
  66. {
  67. case 'h':
  68. show_help(argv[0]);
  69. exit(EXIT_SUCCESS);
  70. break;
  71. case 's':
  72. daemonize_process();
  73. error_code = run_server(PORT);
  74. break;
  75. case 'r':
  76. error_code = run_client("reboot", optarg, PORT);
  77. break;
  78. case 'p':
  79. error_code = run_client("poweroff", optarg, PORT);
  80. break;
  81. }
  82. }
  83. return error_code;
  84. }