Created
April 18, 2012 13:10
-
-
Save r4um/2413457 to your computer and use it in GitHub Desktop.
spawn a cmd redirect stdout/stder/stdin (helpful in cron)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/ruby | |
require 'optparse' | |
class SpawnerOptions | |
def self.parse(args) | |
options = {} | |
options[:stdin] = '/dev/null' | |
options[:stdout] = '/dev/null' | |
options[:stderr] = '/dev/null' | |
options[:wdir] = '/tmp' | |
opts = OptionParser.new do |opts| | |
opts.banner = "Usage: #{__FILE__} [options]" | |
opts.separator "" | |
opts.on("--stdout FILE", "Redirect STDOUT to FILE, "\ | |
"default #{options[:stdout]}") do |f| | |
options[:stdout] = f | |
end | |
opts.on("--stderr FILE", "Redirect STDERR to FILE, "\ | |
"default #{options[:stderr]}") do |f| | |
options[:stderr] = f | |
end | |
opts.on("--stdin FILE", "Redirect STDIN to FILE, "\ | |
"default #{options[:stdin]}") do |f| | |
options[:stdin] = f | |
end | |
opts.on("--pid-file FILE", "Write and do PID check to/from FILE") do |f| | |
options[:pidfile] = f | |
end | |
opts.on("--command CMD", "Exec CMD") do |c| | |
options[:cmd] = c | |
end | |
opts.on("--wdir DIR", "Change to dir DIR, default #{options[:wdir]}") do |c| | |
options[:wdir] = c | |
end | |
opts.on_tail("-h", "--help", "Show this message") do | |
puts opts | |
exit | |
end | |
end | |
begin | |
opts.parse!(args) | |
raise OptionParser::MissingArgument, "--pid-file, no pid file given."\ | |
if not options[:pidfile] | |
raise OptionParser::MissingArgument, "--command, no command given."\ | |
if not options[:cmd] | |
rescue SystemExit | |
exit | |
rescue Exception => e | |
puts "Error " + e.to_s, "#{__FILE__} -h for options." | |
exit | |
end | |
options | |
end | |
end | |
opts = SpawnerOptions.parse(ARGV) | |
if File.exists? opts[:pidfile] | |
pid = File.open(opts[:pidfile]).read.strip.to_i | |
begin | |
if Process.kill(0, pid) | |
puts "#{Time.now.to_s} Already running pid #{pid}" | |
exit(1) | |
end | |
rescue Errno::ESRCH | |
end | |
end | |
pid = fork do | |
Dir.chdir(opts[:wdir]) | |
STDIN.reopen(opts[:stdin], 'r') | |
STDOUT.reopen(opts[:stdout], 'w') | |
STDERR.reopen(opts[:stderr], 'w') | |
exec opts[:cmd] | |
end | |
File.open opts[:pidfile], 'w' do |f| | |
f.write pid | |
puts "#{Time.now.to_s} wrote pid #{pid} to #{opts[:pidfile]}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment