summaryrefslogtreecommitdiff
path: root/cscmd/daemon.c
blob: 80ad4eded6d615b14977f410dc9bd0e12b5ca40b (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
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <fcntl.h>
#include <paths.h>
#include <unistd.h>

#include <daemon.h>

int daemon( int nochdir, int noclose )
{
  int fd;

  switch( fork() )
  {
    case -1:
      return( -1 );
    case 0:
      break;
    default:
      _exit( 0 ); /* direct use kernel exit */
  }

  if( setsid() == -1 ) return( -1 );
  if( !nochdir ) chdir( "/" );
  if( noclose ) return( 0 );

  fd = open( _PATH_DEVNULL, O_RDWR, 0 );
  if( fd != -1 )
  {
    dup2( fd, STDIN_FILENO );
    dup2( fd, STDOUT_FILENO );
    dup2( fd, STDERR_FILENO );
    if( fd > 2 ) close( fd );
  }
  return( 0 );
}