Statistics
| Branch: | Tag: | Revision:

dvbd / src / signals.cpp @ 2cecea08

History | View | Annotate | Download (2.22 KB)

1
/*
2
  Copyright 2003 John Knottenbelt
3
  
4
  This program is free software; you can redistribute it and/or modify
5
  it under the terms of the GNU General Public License as published by
6
  the Free Software Foundation; either version 2 of the License, or
7
  (at your option) any later version.
8
 
9
  This program is distributed in the hope that it will be useful,
10
  but WITHOUT ANY WARRANTY; without even the implied warranty of
11
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
  GNU General Public License for more details.
13
 
14
  You should have received a copy of the GNU General Public License
15
  along with this program; if not, write to the Free Software
16
  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
17
*/
18

    
19
#include "config.h"
20
#include "configfile.h"
21

    
22
#include <sys/types.h>
23
#include <sys/stat.h>
24
#include <fcntl.h>
25
#include <unistd.h>
26
#include <signal.h>
27
#include <cerrno>
28
#include <cstring>
29
#include <fstream>
30
#include <iostream>
31

    
32
void setupSignalHandlers()
33
{
34
  struct sigaction act;
35
  sigset_t set;
36

    
37
  sigemptyset(&set);
38

    
39
  act.sa_handler = SIG_IGN;
40
  act.sa_mask = set;
41
  act.sa_flags = 0;
42

    
43
  sigaction(SIGPIPE, &act, 0);
44
}
45

    
46
bool daemonize(ConfigFile &config)
47
{
48
  std::string logfile = config.get("log");
49
  int fd = open(logfile.c_str(), O_WRONLY|O_APPEND|O_CREAT);
50
  if (fd == -1) {
51
    std::cerr << "Failed to open log file " << logfile << "\n";
52
    return false;
53
  }
54

    
55
  close(0);
56
  close(1);
57
  close(2);
58

    
59
  int devnull = open("/dev/null", O_RDONLY);
60

    
61
  dup2(devnull, 0);
62
  dup2(fd, 1);
63
  dup2(fd, 2);
64
  close(fd);
65

    
66
  // Fork #1
67
  pid_t pid = fork();
68
  if (pid < 0) {
69
    std::cerr << "Failed to fork: " << strerror(errno) << "\n";
70
    return false;
71
  }
72

    
73
  if (pid > 0)                         // Exit the first parent
74
    exit(0);
75

    
76
  chdir("/");
77
  umask(022);
78
  setsid();
79

    
80
  // Fork #2
81
  pid_t pid2 = fork();
82
  if (pid2 < 0) {
83
    std::cerr << "Failed to fork (2): " << strerror(errno) << "\n";
84
    return false;
85
  }
86

    
87
  if (pid2 > 0)                        // Exit the second parent
88
    exit(0);
89
  
90
  // Write PID file
91

    
92
  std::string pidfile = config.get("pid");
93
  std::ofstream pidf(pidfile.c_str());
94
  if (!pidf) 
95
    std::cerr << "Warning: could not open " << pidfile << " for writing pid\n";
96
  else {
97
    pidf << getpid() << "\n";
98
    pidf.close();
99
  }
100
    
101
  return true;
102
}