Skip to content

Instantly share code, notes, and snippets.

@kreeger
Created January 7, 2012 18:44
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save kreeger/1575604 to your computer and use it in GitHub Desktop.
Ruby: Minecraft process launcher
#!/usr/bin/env ruby
# Minecraft server launcher, by Benjamin Kreeger <ben@kree.gr>.
# Feel free to shamelessly steal this script. I don't care.
# I renamed mine to `mc_server` and did a `chmod +x` on it so I
# wouldn't have to type `ruby mc_server.rb` on it every time I
# wanted to launch my server in the background.
#
# Make sure this is in the same directory as your
# `minecraft_server.jar` file. I haven't tested it otherwise, and
# I'm sure it won't work.
#
# It expects you to have a Java runtime installed, and it expects
# your Minecraft server jar to be named `minecraft_server.jar`. If
# you've renamed it, feed `--jar new-jar-name.jar` to the script.
#
# For more help and options, run it with an `-h` or `--help` flag.
#
# Enjoy.
require 'logger'
require 'optparse'
PIDFILE = 'pidfile'
options = {}
OptionParser.new do |opts|
opts.banner = 'Minecraft server launcher. Usage: mc_server.rb [options]'
options[:stop] = false
opts.on('-s', '--stop', 'Stop any running server.') do
options[:stop] = true
end
options[:verbose] = false
opts.on('-v', '--[no-]verbose', 'Run verbosely.') do
options[:verbose] = true
end
options[:memory] = 1024
opts.on('-m', '--memory AMOUNT', 'Allocate AMOUNT to server memory.') do |amount|
options[:memory] = amount
end
options[:jar] = 'minecraft_server.jar'
opts.on('-j', '--jar /PATH/TO/MINECRAFT/JAR', 'Specify special path to server.') do |jar|
options[:jar] = jar
end
opts.on_tail('-h', '--help', 'Show this message') do
puts opts
exit
end
end.parse!
log = Logger.new STDOUT
log.level = options[:verbose] ? Logger::DEBUG : Logger::INFO
begin
pid = File.open(PIDFILE, 'r') { |f| f.read }
rescue Errno::ENOENT => e
log.warn e.message
log.warn "No pidfile found. Creating one."
pid = nil
end
file = File.open(PIDFILE, 'w+')
if options[:stop]
if pid.nil? or pid.empty?
log.error "No existing process found. Terminating."
else
pid = pid.to_i
begin
Process.kill 'HUP', pid
log.info "Found existing process ID # #{pid}. Terminating."
rescue Errno::ESRCH => e
log.error "Found process ID # #{pid}, but it is not running. Terminating."
end
end
file.puts ''
exit
end
segments = [
"java",
"-Xmx#{options[:memory]}M",
"-Xms#{options[:memory]}M",
"-jar",
options[:jar],
['nogui'].join(' '),
]
command = segments.join ' '
log.info "Starting Minecraft server with #{options[:memory]}M memory."
pid = spawn command, :err => "/dev/null", :out => "/dev/null"
file.puts pid
Process.detach pid
log.info "Minecraft server started with process ID # #{pid}."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment