mycodaemon.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * mycodaemon.c
  3. */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <unistd.h>
  7. #include <signal.h>
  8. #include <sys/types.h>
  9. #include <sys/stat.h>
  10. #include <syslog.h>
  11. #include "../src/myco-daemon.c"
  12. static void daemonize()
  13. {
  14. pid_t pid;
  15. /* Fork off the parent process */
  16. pid = fork();
  17. /* An error occurred */
  18. if (pid < 0)
  19. exit(EXIT_FAILURE);
  20. /* Success: Let the parent terminate */
  21. if (pid > 0)
  22. exit(EXIT_SUCCESS);
  23. /* On success: The child process becomes session leader */
  24. if (setsid() < 0)
  25. exit(EXIT_FAILURE);
  26. /* Catch, ignore and handle signals */
  27. //TODO: Implement a working signal handler */
  28. signal(SIGCHLD, SIG_IGN);
  29. signal(SIGHUP, SIG_IGN);
  30. /* Fork off for the second time*/
  31. pid = fork();
  32. /* An error occurred */
  33. if (pid < 0)
  34. exit(EXIT_FAILURE);
  35. /* Success: Let the parent terminate */
  36. if (pid > 0)
  37. exit(EXIT_SUCCESS);
  38. /* Set new file permissions */
  39. umask(0);
  40. /* Change the working directory to the root directory */
  41. /* or another appropriated directory */
  42. chdir("/");
  43. /* Close all open file descriptors */
  44. int x;
  45. for (x = sysconf(_SC_OPEN_MAX); x>0; x--)
  46. {
  47. close (x);
  48. }
  49. /* Open the log file */
  50. openlog ("firstdaemon", LOG_PID, LOG_DAEMON);
  51. }
  52. int main() {
  53. daemonize();
  54. syslog(LOG_NOTICE, "mycodaemon started.");
  55. if (myco_daemon_start(getpid(), "192.168.0.35", "192.168.0.10") == -1) {
  56. return EXIT_FAILURE;
  57. }
  58. syslog (LOG_NOTICE, "mycodaemon terminated.");
  59. closelog();
  60. return EXIT_SUCCESS;
  61. }