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