# dedicated.cpp

Go to the documentation of this file.

    00001 /* $Id: dedicated.cpp 26098 2013-11-25 09:20:35Z rubidium $ */
    00002
    00003 /*
    00004  * This file is part of OpenTTD.
    00005  * 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.
    00006  * 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.
    00007  * 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/>.
    00008  */
    00009
    00012 #include "stdafx.h"
    00013
    00014 #ifdef ENABLE_NETWORK
    00015
    00016 char *_log_file = NULL;
    00017 FILE *_log_fd   = NULL;
    00018
    00019 #if defined(UNIX) && !defined(__MORPHOS__)
    00020
    00021 #include <unistd.h>
    00022
    00023 #if (defined(SUNOS) && !defined(_LP64) && !defined(_I32LPx)) || defined(__HAIKU__)
    00024 /* Solaris has, in certain situation, pid_t defined as long, while in other
    00025  *  cases it has it defined as int... this handles all cases nicely.
    00026  * Haiku has also defined pid_t as a long.
    00027  */
    00028 # define PRINTF_PID_T "%ld"
    00029 #else
    00030 # define PRINTF_PID_T "%d"
    00031 #endif
    00032
    00033 void DedicatedFork()
    00034 {
    00035   /* Fork the program */
    00036   pid_t pid = fork();
    00037   switch (pid) {
    00038     case -1:
    00039       perror("Unable to fork");
    00040       exit(1);
    00041
    00042     case 0: { // We're the child
    00043       /* Open the log-file to log all stuff too */
    00044       _log_fd = fopen(_log_file, "a");
    00045       if (_log_fd == NULL) {
    00046         perror("Unable to open logfile");
    00047         exit(1);
    00048       }
    00049       /* Redirect stdout and stderr to log-file */
    00050       if (dup2(fileno(_log_fd), fileno(stdout)) == -1) {
    00051         perror("Rerouting stdout");
    00052         exit(1);
    00053       }
    00054       if (dup2(fileno(_log_fd), fileno(stderr)) == -1) {
    00055         perror("Rerouting stderr");
    00056         exit(1);
    00057       }
    00058       break;
    00059     }
    00060
    00061     default:
    00062       /* We're the parent */
    00063       printf("Loading dedicated server...\n");
    00064       printf("  - Forked to background with pid " PRINTF_PID_T "\n", pid);
    00065       exit(0);
    00066   }
    00067 }
    00068 #endif
    00069
    00070 #else
    00071
    00073 void DedicatedFork() {}
    00074
    00075 #endif /* ENABLE_NETWORK */