File: daemon.c

package info (click to toggle)
cvsd 1.0.13
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 1,372 kB
  • ctags: 157
  • sloc: sh: 4,552; ansic: 1,868; perl: 198; makefile: 147
file content (72 lines) | stat: -rw-r--r-- 1,914 bytes parent folder | download | duplicates (5)
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
72
/*
   daemon.c - implementation of daemon() for systems that lack it

   Copyright (C) 2002, 2003 Arthur de Jong

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

   This program 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 General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin St, 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;
}