daemonize.c 1022 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /* Licensed under BSD-MIT - see LICENSE file for details */
  2. #include <ccan/daemonize/daemonize.h>
  3. #include <unistd.h>
  4. #include <stdlib.h>
  5. #include <sys/types.h>
  6. #include <sys/stat.h>
  7. #include <fcntl.h>
  8. /* This code is based on Stevens Advanced Programming in the UNIX
  9. * Environment. */
  10. bool daemonize(void)
  11. {
  12. pid_t pid;
  13. /* Separate from our parent via fork, so init inherits us. */
  14. if ((pid = fork()) < 0)
  15. return false;
  16. if (pid != 0)
  17. exit(0);
  18. /* Don't hold files open. */
  19. close(STDIN_FILENO);
  20. close(STDOUT_FILENO);
  21. close(STDERR_FILENO);
  22. /* Many routines write to stderr; that can cause chaos if used
  23. * for something else, so set it here. */
  24. if (open("/dev/null", O_WRONLY) != 0)
  25. return false;
  26. if (dup2(0, STDERR_FILENO) != STDERR_FILENO)
  27. return false;
  28. close(0);
  29. /* Session leader so ^C doesn't whack us. */
  30. setsid();
  31. /* Move off any mount points we might be in. */
  32. if (chdir("/") != 0)
  33. return false;
  34. /* Discard our parent's old-fashioned umask prejudices. */
  35. umask(0);
  36. return true;
  37. }