alix-switchd.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. /*
  2. * alix-switchd.c
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 2 of the License, or
  7. * (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 <signal.h>
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include <string.h>
  18. #include <syslog.h>
  19. #include <time.h>
  20. #include <unistd.h>
  21. #include <sys/io.h>
  22. #include <sys/stat.h>
  23. #include <sys/types.h>
  24. #define SCRIPT "/etc/alix-switch"
  25. #define GPIOBASE 0x6100
  26. typedef void (*sighandler_t)(int);
  27. static sighandler_t handle_signal (int sig_nr, sighandler_t signalhandler) {
  28. struct sigaction neu_sig, alt_sig;
  29. neu_sig.sa_handler = signalhandler;
  30. sigemptyset(&neu_sig.sa_mask);
  31. neu_sig.sa_flags = SA_RESTART;
  32. if (sigaction (sig_nr, &neu_sig, &alt_sig) < 0)
  33. return SIG_ERR;
  34. return alt_sig.sa_handler;
  35. }
  36. static void start_daemon (void) {
  37. int i;
  38. pid_t pid, sid;
  39. handle_signal(SIGHUP, SIG_IGN);
  40. if ((pid = fork ()) != 0)
  41. exit(EXIT_FAILURE);
  42. umask(0);
  43. if ((sid = setsid()) < 0)
  44. exit(EXIT_FAILURE);
  45. chdir("/");
  46. for (i = sysconf(_SC_OPEN_MAX); i > 0; i--)
  47. close(i);
  48. }
  49. int main(int argc, char *argv[]) {
  50. int i;
  51. unsigned long bPort = 0;
  52. struct timespec sleep;
  53. int bDaemon = 0, bSwitch = 0, bState = 0;
  54. for(i = 1; i < argc; i++) {
  55. if (!strcasecmp(argv[i], "-d") || !strcasecmp(argv[i], "--daemon")) {
  56. bDaemon = 1;
  57. } else {
  58. printf( "\nusage: %s [-d | --daemon]\n", argv[0]);
  59. exit(EXIT_FAILURE);
  60. }
  61. }
  62. if (iopl(3)) {
  63. fprintf( stderr, "Could not set I/O permissions to level 3\n");
  64. exit(EXIT_FAILURE);
  65. }
  66. if (bDaemon)
  67. start_daemon();
  68. sleep.tv_sec = 0;
  69. sleep.tv_nsec = 50000000;
  70. while(1) {
  71. bPort = inl(GPIOBASE + 0xB0);
  72. if ((bPort & 0x100) == 0)
  73. bState = 1;
  74. else
  75. bState = 0;
  76. if (bState && !bSwitch)
  77. system(SCRIPT " on");
  78. bSwitch = bState;
  79. nanosleep(&sleep, NULL);
  80. }
  81. if (iopl(0)) {
  82. fprintf(stderr, "Could not set I/O permissions to level 0");
  83. exit(EXIT_FAILURE);
  84. }
  85. return EXIT_SUCCESS;
  86. }