- Added daemon() replacement.
[oweals/tinc.git] / lib / daemon.c
1 /*
2     daemon.c -- replacement daemon() for platforms that do not have it
3     Copyright (C) 2000 Ivo Timmermans <itimmermans@bigfoot.com>,
4                   2000 Guus Sliepen <guus@sliepen.warande.net>
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20     $Id: daemon.c,v 1.1.2.1 2000/11/24 23:30:50 guus Exp $
21 */
22
23 #include "config.h"
24
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <fcntl.h>
28 #include <unistd.h>
29 #include <stdio.h>
30
31 #include <system.h>
32
33 #ifndef HAVE_DAEMON
34 int daemon(int nochdir, int noclose)
35 {
36   pid_t pid;
37   int fd;
38   
39   pid = fork();
40   
41   /* Check if forking failed */
42     
43   if(pid < 0)
44     {
45       perror("fork");
46       exit(-1);
47     }
48
49   /* If we are the parent, terminate */
50   
51   if(pid)
52     exit(0);
53
54   /* Detach by becoming the new process group leader */
55   
56   if(setsid() < 0)
57     {
58       perror("setsid");
59       return -1;
60     }
61   
62   /* Change working directory to the root (to avoid keeping mount points busy) */
63   
64   if(!nochdir)
65     {
66       chdir("/");
67     }
68     
69   /* Redirect stdin/out/err to /dev/null */
70
71   if(!noclose)
72     {
73       fd = open("/dev/null", O_RDWR);
74
75       if(fd < 0)
76         {
77           perror("opening /dev/null");
78           return -1;
79         }
80         else
81         {
82           dup2(fd, 0);
83           dup2(fd, 1);
84           dup2(fd, 2);
85         }
86     }
87 }
88 #endif