Statistics
| Branch: | Tag: | Revision:

dvbd / src / signals.cpp @ bcb74979

History | View | Annotate | Download (2.25 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
#include <stdlib.h>
32

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

    
38
  sigemptyset(&set);
39

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

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

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

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

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

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

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

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

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

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

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

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