OpenTTD
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 
12 char *_log_file = nullptr;
13 FILE *_log_fd = nullptr;
14 
15 #if defined(UNIX)
16 
17 #include <unistd.h>
18 
19 #include "safeguards.h"
20 
21 #if defined(SUNOS) && !defined(_LP64) && !defined(_I32LPx)
22 /* Solaris has, in certain situation, pid_t defined as long, while in other
23  * cases it has it defined as int... this handles all cases nicely.
24  */
25 # define PRINTF_PID_T "%ld"
26 #else
27 # define PRINTF_PID_T "%d"
28 #endif
29 
30 void DedicatedFork()
31 {
32  /* Fork the program */
33  pid_t pid = fork();
34  switch (pid) {
35  case -1:
36  perror("Unable to fork");
37  exit(1);
38 
39  case 0: { // We're the child
40  /* Open the log-file to log all stuff too */
41  _log_fd = fopen(_log_file, "a");
42  if (_log_fd == nullptr) {
43  perror("Unable to open logfile");
44  exit(1);
45  }
46  /* Redirect stdout and stderr to log-file */
47  if (dup2(fileno(_log_fd), fileno(stdout)) == -1) {
48  perror("Rerouting stdout");
49  exit(1);
50  }
51  if (dup2(fileno(_log_fd), fileno(stderr)) == -1) {
52  perror("Rerouting stderr");
53  exit(1);
54  }
55  break;
56  }
57 
58  default:
59  /* We're the parent */
60  printf("Loading dedicated server...\n");
61  printf(" - Forked to background with pid " PRINTF_PID_T "\n", pid);
62  exit(0);
63  }
64 }
65 #endif
FILE * _log_fd
File to reroute output of a forked OpenTTD to.
Definition: dedicated.cpp:13
char * _log_file
File to reroute output of a forked OpenTTD to.
Definition: dedicated.cpp:12
Definition of base types and functions in a cross-platform compatible way.
A number of safeguards to prevent using unsafe methods.