indigoparadox

mcdaemon.c

May 17th, 2013
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.56 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <sys/stat.h>
  3. #include <fcntl.h>
  4. #include <signal.h>
  5. #include <unistd.h>
  6.  
  7. #define FIFO_PATH "/minecraft/console"
  8. #define MC_JAVA_MEM "1024M"
  9. #define COMMAND_STOP "stop\n"
  10.  
  11. int gi_pipe_mc_stdin[2];
  12.  
  13. void signal_handler( int i_signum_in ) {
  14.    if( SIGTERM == i_signum_in ) {
  15.       /* Send the daemon the stop command and wait for it to close. */
  16.       write( gi_pipe_mc_stdin[1], COMMAND_STOP, sizeof( COMMAND_STOP ) );
  17.       wait( NULL );
  18.  
  19.       /* Cleanup */
  20.       close( gi_pipe_mc_stdin[1] );
  21.  
  22.       _exit( 0 );
  23.    }
  24. }
  25.  
  26. int main( void ) {
  27.    int i_mc_pid; /* The PID of the forked child process. */
  28.    char* mc_argv[] = {
  29.       "/usr/bin/java",
  30.       "-Xmx"MC_JAVA_MEM,
  31.       "-Xms"MC_JAVA_MEM,
  32.       "-jar",
  33.       "/minecraft/craftbukkit.jar"
  34.    };
  35.  
  36.    /* Setup a pipe to send commands to the child. */
  37.    if( pipe( gi_pipe_mc_stdin ) ) {
  38.       fprintf( stderr, "Unable to open communication pipe." );
  39.       _exit( 1 );
  40.    }
  41.  
  42.    signal( SIGTERM, signal_handler );
  43.  
  44.    /* Fork and start the MC daemon. */
  45.    i_mc_pid = fork();
  46.    if( 0 == i_mc_pid ) {
  47.       /* This is the child process. */
  48.       /* Close existing stdin/stdout and attach them to the parent's pipes. */
  49.       close( 0 );
  50.       dup2( gi_pipe_mc_stdin[0], 0 );
  51.  
  52.       /* Start the daemon. */
  53.       execv( mc_argv[0], mc_argv );
  54.  
  55.    } else if( 0 < i_mc_pid ) {
  56.       /* This is the parent process. */
  57.  
  58.       close( gi_pipe_mc_stdin[0] );
  59.  
  60.       /* Wait until we get SIGTERM or the child dies. */
  61.       wait( NULL );
  62.    }
  63.  
  64.    return 0;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment