system_ctl_app.c 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <fcntl.h>
  5. #include <string.h>
  6. #include <errno.h>
  7. #include <sys/reboot.h>
  8. #include <sys/types.h>
  9. #include <sys/wait.h>
  10. #define DEV_PATH "/dev/power"
  11. #define BUFFER_SIZE 2
  12. void execute_command(const char *cmd) {
  13. pid_t pid = fork();
  14. if (pid == -1) {
  15. perror("fork failed");
  16. return;
  17. }
  18. if (pid == 0) {
  19. execl("/bin/sh", "sh", "-c", cmd, NULL);
  20. perror("execl failed");
  21. exit(EXIT_FAILURE);
  22. } else {
  23. int status;
  24. waitpid(pid, &status, 0);
  25. }
  26. }
  27. void reboot_system() {
  28. printf("reboot command received, system rebooting...\n");
  29. sync();
  30. execute_command("reboot");
  31. }
  32. void shutdown_system() {
  33. printf("shutdown command received, system shutting down...\n");
  34. sync();
  35. execute_command("shutdown -h now");
  36. }
  37. int main() {
  38. int fd;
  39. char buf[BUFFER_SIZE];
  40. ssize_t nread;
  41. fd = open(DEV_PATH, O_RDONLY);
  42. if (fd == -1) {
  43. fprintf(stderr, "cannot open device node %s: %s\n",
  44. DEV_PATH, strerror(errno));
  45. fprintf(stderr, "please ensure:\n");
  46. fprintf(stderr, "1. device node /dev/power exists\n");
  47. fprintf(stderr, "2. sufficient permissions to access\n");
  48. fprintf(stderr, "3. kernel driver is loaded\n");
  49. return EXIT_FAILURE;
  50. }
  51. printf("monitoring %s, waiting for commands...\n", DEV_PATH);
  52. printf("'r' -> reboot system\n");
  53. printf("'p' -> graceful shutdown\n");
  54. printf("press Ctrl+C to exit\n\n");
  55. while (1) {
  56. nread = read(fd, buf, sizeof(buf) - 1);
  57. if (nread == -1) {
  58. if (errno == EINTR) {
  59. continue;
  60. }
  61. perror("read device node failed");
  62. break;
  63. } else if (nread == 0) {
  64. printf("device node closed, exiting\n");
  65. break;
  66. }
  67. buf[nread] = '\0';
  68. for (int i = 0; i < nread; i++) {
  69. char ch = buf[i];
  70. switch (ch) {
  71. case 'r':
  72. case 'R':
  73. printf("detected character '%c'\n", ch);
  74. reboot_system();
  75. break;
  76. case 'p':
  77. case 'P':
  78. printf("detected character '%c'\n", ch);
  79. shutdown_system();
  80. break;
  81. default:
  82. printf("unknown character: '%c' (ASCII: %d)\n", ch, ch);
  83. break;
  84. }
  85. }
  86. }
  87. close(fd);
  88. return EXIT_SUCCESS;
  89. }