daemon_lin.cpp
Go to the documentation of this file.
1 
11 #include "daemon.h"
12 
13 #include <sys/types.h>
14 #include <sys/stat.h>
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <fcntl.h>
18 #include <errno.h>
19 #include <unistd.h>
20 #include <syslog.h>
21 #include <string.h>
22 
23 #include <mutex>
24 #include <condition_variable>
25 #include <iostream>
26 #include <signal.h>
27 
28 namespace
29 {
30 
31 OpcUa::Daemon * DaemonInstance = 0;
32 
33 void TerminateSignal(int signum)
34 {
35  std::cout << "terminating.." << std::endl;
36 
37  if (DaemonInstance)
38  {
39  DaemonInstance->Terminate();
40  DaemonInstance = nullptr;
41  }
42 }
43 
44 }
45 
46 namespace OpcUa
47 {
49 {
50  if (signal(SIGTERM, TerminateSignal) == SIG_ERR)
51  {
52  std::cerr << "unable to set SIGTERM handler" << std::endl;
53  }
54 
55  if (signal(SIGINT, TerminateSignal) == SIG_ERR)
56  {
57  std::cerr << "unable to set SIGINT handler" << std::endl;
58  }
59 
60  if (signal(SIGSTOP, TerminateSignal) == SIG_ERR)
61  {
62  std::cerr << "unable to set SIGSTOP handler" << std::endl;
63  }
64 
65  DaemonInstance = this;
66 }
67 
68 void Daemon::Daemonize(const std::string & logFile)
69 {
70  pid_t pid, sid;
71 
72  pid = fork();
73 
74  if (pid < 0)
75  {
76  std::cerr << "Failed to fork: " << strerror(errno) << std::endl;
77  exit(EXIT_FAILURE);
78  }
79 
80  if (pid > 0)
81  {
82  exit(EXIT_SUCCESS);
83  }
84 
85  umask(0);
86 
87  sid = setsid();
88 
89  if (sid < 0)
90  {
91  std::cerr << "setsid() failed: " << strerror(errno) << std::endl;
92  exit(EXIT_FAILURE);
93  }
94 
95  if ((chdir("/")) < 0)
96  {
97  std::cerr << "Cannot change dir. " << strerror(errno) << std::endl;
98  exit(EXIT_FAILURE);
99  }
100 
101  if (!logFile.empty())
102  {
103  FILE * tmp = fopen(logFile.c_str(), "w");
104 
105  if (!tmp)
106  {
107  std::cerr << "Cannot open log file " << logFile << ". " << strerror(errno) << std::endl;
108  exit(EXIT_FAILURE);
109  }
110 
111  close(STDIN_FILENO);
112  close(STDOUT_FILENO);
113  close(STDERR_FILENO);
114 
115  dup2(fileno(tmp), STDOUT_FILENO);
116  dup2(fileno(tmp), STDERR_FILENO);
117  }
118 }
119 }
void Terminate()
Definition: daemon.cpp:32
OPC UA Address space part. GNU LGPL.
void Daemonize(const std::string &str)
Definition: daemon_lin.cpp:68
void SetTerminateHandlers()
Definition: daemon_lin.cpp:48


ros_opcua_impl_freeopcua
Author(s): Denis Štogl
autogenerated on Tue Jan 19 2021 03:06:04