blob: dfd26b3627dab1e93903720f8796a75328b62f01 [file] [log] [blame]
paul718e3742002-12-13 20:15:29 +00001/*
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
23#include <zebra.h>
24
25#ifndef HAVE_DAEMON
26
27/* Daemonize myself. */
28int
29daemon (int nochdir, int noclose)
30{
31 pid_t pid;
32
33 pid = fork ();
34
35 /* In case of fork is error. */
36 if (pid < 0)
37 {
38 perror ("fork");
39 return -1;
40 }
41
42 /* In case of this is parent process. */
43 if (pid != 0)
44 exit (0);
45
46 /* Become session leader and get pid. */
47 pid = setsid();
48
49 if (pid < -1)
50 {
51 perror ("setsid");
52 return -1;
53 }
54
55 /* Change directory to root. */
56 if (! nochdir)
57 chdir ("/");
58
59 /* File descriptor close. */
60 if (! noclose)
61 {
62 int fd;
63
64 fd = open ("/dev/null", O_RDWR, 0);
65 if (fd != -1)
66 {
67 dup2 (fd, STDIN_FILENO);
68 dup2 (fd, STDOUT_FILENO);
69 dup2 (fd, STDERR_FILENO);
70 if (fd > 2)
71 close (fd);
72 }
73 }
74
75 umask (0027);
76
77 return 0;
78}
79
80#endif /* HAVE_DAEMON */