Advertisement
MdSadmanSiraj

hw_daemon_mssiraj.c

Jul 20th, 2022
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.90 KB | None | 0 0
  1. /*
  2. COMPILATION COMMAND:
  3. arm-linux-gnueabi-gcc -static -o hw_daemon_mssiraj hw_daemon_mssiraj.c
  4. */
  5.  
  6. #include <stdio.h>
  7. #include <stdarg.h>
  8. #include <stdlib.h>
  9. #include <sys/types.h>
  10. #include <sys/times.h>
  11. #include <sys/stat.h>
  12. #include <sys/param.h>
  13. #include <unistd.h>
  14. #include <syslog.h>
  15. #include <errno.h>
  16. #include <signal.h>
  17. #include <inttypes.h>
  18. #include <string.h>
  19. #include <time.h>
  20.  
  21. #define OK 0
  22. #define true 1
  23. #define ERR_WTF 1
  24. #define ERR_FORK 1
  25. #define ERR_SETSID 1
  26. #define ERR_CHDIR 1
  27. #define ERR_TIME 1
  28. #define ERROR_FORMAT "ERROR MESSAGE: %s"
  29. #define DAEMON_NAME "sample_daemon_mssiraj"
  30.  
  31. static void _signal_handler(const int signal) {
  32.     switch(signal) {
  33.         case SIGHUP:
  34.             break;
  35.        
  36.         case SIGTERM:
  37.             syslog(LOG_INFO, "received SIGTERM, exiting.");
  38.             closelog();
  39.             exit(OK);
  40.             break;
  41.     default:
  42.         syslog(LOG_INFO, "received unhandled signal");
  43.     }
  44. }
  45.  
  46. static int _do_work(void) {
  47.     while(1) {
  48.         time_t present_time = time(NULL);
  49.         struct tm *ptm = localtime(&present_time);
  50.        
  51.         if (ptm == NULL) {
  52.             return ERR_TIME;
  53.             }
  54.        
  55.         syslog(LOG_INFO, "Present Time: %d:%d:%d", ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
  56.         sleep(1);
  57.         }
  58. }
  59.    
  60. int main(void) {
  61.     openlog(DAEMON_NAME, LOG_PID | LOG_NDELAY | LOG_NOWAIT, LOG_DAEMON);
  62.     syslog(LOG_INFO, "Starting hw_daemon_mssiraj");
  63.    
  64.     pid_t pid = fork();
  65.    
  66.     if (pid < 0) {
  67.         syslog(LOG_ERR, ERROR_FORMAT, strerror(errno));
  68.         return ERR_FORK;
  69.     }
  70.    
  71.     if (pid > 0) {
  72.         return OK;
  73.     }
  74.    
  75.     if (setsid() < -1){
  76.         syslog(LOG_ERR, ERROR_FORMAT, strerror(errno));
  77.         return ERR_SETSID;
  78.     }
  79.    
  80.     close(STDIN_FILENO);
  81.     close(STDOUT_FILENO);
  82.     close(STDERR_FILENO);
  83.    
  84.     umask(S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
  85.    
  86.     if (chdir("/") < 0) {
  87.         syslog(LOG_ERR, ERROR_FORMAT, strerror(errno));
  88.         return ERR_CHDIR;
  89.     }
  90.    
  91.     signal(SIGTERM, _signal_handler);
  92.     signal(SIGHUP, _signal_handler);
  93.    
  94.     _do_work();
  95.    
  96.     return ERR_WTF;
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement