OpenTTD Source  20241121-master-g67a0fccfad
dedicated.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of OpenTTD.
3  * OpenTTD 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, version 2.
4  * OpenTTD 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.
5  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6  */
7 
10 #include "stdafx.h"
11 #include "fileio_func.h"
12 #include "debug.h"
13 
14 std::string _log_file;
15 std::optional<FileHandle> _log_fd;
16 
17 #if defined(UNIX)
18 
19 #include <unistd.h>
20 
21 #include "safeguards.h"
22 
23 void DedicatedFork()
24 {
25  /* Fork the program */
26  pid_t pid = fork();
27  switch (pid) {
28  case -1:
29  perror("Unable to fork");
30  exit(1);
31 
32  case 0: { // We're the child
33  /* Open the log-file to log all stuff too */
35  if (!_log_fd.has_value()) {
36  perror("Unable to open logfile");
37  exit(1);
38  }
39  /* Redirect stdout and stderr to log-file */
40  if (dup2(fileno(*_log_fd), fileno(stdout)) == -1) {
41  perror("Rerouting stdout");
42  exit(1);
43  }
44  if (dup2(fileno(*_log_fd), fileno(stderr)) == -1) {
45  perror("Rerouting stderr");
46  exit(1);
47  }
48  break;
49  }
50 
51  default:
52  /* We're the parent */
53  Debug(net, 0, "Loading dedicated server...");
54  Debug(net, 0, " - Forked to background with pid {}", pid);
55  exit(0);
56  }
57 }
58 #endif
static std::optional< FileHandle > Open(const std::string &filename, const std::string &mode)
Open an RAII file handle if possible.
Definition: fileio.cpp:1170
Functions related to debugging.
#define Debug(category, level, format_string,...)
Ouptut a line of debugging information.
Definition: debug.h:37
std::string _log_file
Filename to reroute output of a forked OpenTTD to.
Definition: dedicated.cpp:14
std::optional< FileHandle > _log_fd
File to reroute output of a forked OpenTTD to.
Definition: dedicated.cpp:15
Functions for Standard In/Out file operations.
A number of safeguards to prevent using unsafe methods.
Definition of base types and functions in a cross-platform compatible way.