Arthur de Jong

Open Source / Free Software developer

summaryrefslogtreecommitdiffstats
path: root/compat/daemon.c
blob: e3d5aea72dff232f453a5a288ba44f7ab3ffe03d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
   daemon.c - implementation of daemon() for systems that lack it

   Copyright (C) 2002, 2003, 2008, 2012 Arthur de Jong

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
   02110-1301 USA
*/

#include "daemon.h"

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int daemon(int nochdir, int noclose)
{
  /* change directory */
  if (!nochdir)
    if (chdir("/") != 0)
      return -1;
  /* fork() and exit() to detach from the parent process */
  switch (fork())
  {
    case 0:    /* we are the child */
      break;
    case -1:   /* we are the parent, but have an error */
      return -1;
    default:   /* we are the parent and we're done */
      _exit(0);
  }
  /* become process leader */
  if (setsid() < 0)
  {
    return -1;
  }
  /* fork again so we cannot allocate a pty */
  switch (fork())
  {
    case 0:    /* we are the child */
      break;
    case -1:   /* we are the parent, but have an error */
      return -1;
    default:   /* we are the parent and we're done */
      _exit(0);
  }
  /* close stdin, stdout and stderr and reconnect to /dev/null */
  if (!noclose)
  {
    close(0);   /* stdin */
    close(1);   /* stdout */
    close(2);   /* stderr */
    open("/dev/null", O_RDWR);  /* stdin, fd=0 */
    dup(0);     /* stdout, fd=1 */
    dup(0);     /* stderr, fd=2 */
  }
  return 0;
}