Unix daemon process


/ Published in: C
Save to your folder(s)

Skeleton daemon process for unix


Copy this code and paste it in your HTML
  1. /**
  2.   * Skeleton daemon code.
  3.   * Author: Sukanta K. Hazra <sukanta at hazra dot net>
  4.   */
  5.  
  6. #include <sys/types.h>
  7. #include <sys/stat.h>
  8. #include <fcntl.h>
  9. #include <syslog.h>
  10. #include <stdlib.h>
  11. #include <unistd.h>
  12.  
  13.  
  14. /**
  15.   * This function forks out a child process and exits the parent
  16.   */
  17. int daemon_init(void)
  18. {
  19. pid_t pid;
  20.  
  21. if ((pid = fork()) < 0) {
  22. return -1;
  23. } else if (pid !=0) {
  24. exit(0); /* parent goes bye-bye */
  25. }
  26.  
  27. /* child continues */
  28. setsid(); /* become session leader */
  29.  
  30. chdir("/"); /* change working directory */
  31.  
  32. umask(0); /* clear our file mode creation mask */
  33.  
  34. close(STDIN_FILENO); /* close the unneeded file descriptors */
  35. close(STDOUT_FILENO);
  36. close(STDERR_FILENO);
  37.  
  38. }
  39.  
  40. int main(int argc, char *argv[])
  41. {
  42. daemon_init();
  43.  
  44. /* Execute the processing code here */
  45.  
  46. /* For logging you might want to use syslog or open a log file */
  47. syslog(LOG_ERR, "SKH: Entering the main code section");
  48.  
  49. return 0;
  50. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.