daemon.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * Daemonize routine
  3. * Copyright (C) 1997, 1999 Kunihiro Ishiguro
  4. *
  5. * This file is part of GNU Zebra.
  6. *
  7. * GNU Zebra is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published
  9. * by the Free Software Foundation; either version 2, or (at your
  10. * option) any later version.
  11. *
  12. * GNU Zebra is distributed in the hope that it will be useful, but
  13. * WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with GNU Zebra; see the file COPYING. If not, write to the
  19. * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  20. * Boston, MA 02111-1307, USA.
  21. */
  22. #include <zebra.h>
  23. #include <log.h>
  24. #ifndef HAVE_DAEMON
  25. /* Daemonize myself. */
  26. int
  27. daemon (int nochdir, int noclose)
  28. {
  29. pid_t pid;
  30. pid = fork ();
  31. /* In case of fork is error. */
  32. if (pid < 0)
  33. {
  34. zlog_err ("fork failed: %s", safe_strerror(errno));
  35. return -1;
  36. }
  37. /* In case of this is parent process. */
  38. if (pid != 0)
  39. exit (0);
  40. /* Become session leader and get pid. */
  41. pid = setsid();
  42. if (pid == -1)
  43. {
  44. zlog_err ("setsid failed: %s", safe_strerror(errno));
  45. return -1;
  46. }
  47. /* Change directory to root. */
  48. if (! nochdir)
  49. chdir ("/");
  50. /* File descriptor close. */
  51. if (! noclose)
  52. {
  53. int fd;
  54. fd = open ("/dev/null", O_RDWR, 0);
  55. if (fd != -1)
  56. {
  57. dup2 (fd, STDIN_FILENO);
  58. dup2 (fd, STDOUT_FILENO);
  59. dup2 (fd, STDERR_FILENO);
  60. if (fd > 2)
  61. close (fd);
  62. }
  63. }
  64. umask (0027);
  65. return 0;
  66. }
  67. #endif /* HAVE_DAEMON */