Codefix: Documentation comment in IndustryDirectoryWindow (#13059)
[openttd-github.git] / src / dedicated.cpp
blob1e5ad657dfaf3b20e4a59c20d04c99c225536900
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 */
8 /** @file dedicated.cpp Forking support for dedicated servers. */
10 #include "stdafx.h"
11 #include "fileio_func.h"
12 #include "debug.h"
14 std::string _log_file; ///< Filename to reroute output of a forked OpenTTD to
15 std::optional<FileHandle> _log_fd; ///< File to reroute output of a forked OpenTTD to
17 #if defined(UNIX)
19 #include <unistd.h>
21 #include "safeguards.h"
23 void DedicatedFork()
25 /* Fork the program */
26 pid_t pid = fork();
27 switch (pid) {
28 case -1:
29 perror("Unable to fork");
30 exit(1);
32 case 0: { // We're the child
33 /* Open the log-file to log all stuff too */
34 _log_fd = FileHandle::Open(_log_file, "a");
35 if (!_log_fd.has_value()) {
36 perror("Unable to open logfile");
37 exit(1);
39 /* Redirect stdout and stderr to log-file */
40 if (dup2(fileno(*_log_fd), fileno(stdout)) == -1) {
41 perror("Rerouting stdout");
42 exit(1);
44 if (dup2(fileno(*_log_fd), fileno(stderr)) == -1) {
45 perror("Rerouting stderr");
46 exit(1);
48 break;
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);
58 #endif