From f2e78c476ab95e5d8278e08c7a140e9448a2c8f8 Mon Sep 17 00:00:00 2001 From: Guillaume DOTT Date: Thu, 27 Feb 2014 15:09:10 +0100 Subject: [PATCH] Add option to redirect stdout and stderr to a file When using a daemon, stdout and stderr are redirected to /dev/null. If the program generates an exception and crashes, we can't get the message. This option allows to get everything from stdout and stderr in a file. --- lib/smsd/cli.rb | 11 ++++++++++- lib/smsd/cli/options.rb | 5 +++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/lib/smsd/cli.rb b/lib/smsd/cli.rb index a029f96..1612a80 100644 --- a/lib/smsd/cli.rb +++ b/lib/smsd/cli.rb @@ -13,6 +13,7 @@ module SMSd self.machine = yield block if block_given? init_logger + redirect_output @modem = Biju::Hayes.new(options[:modem], pin: options[:pin]) rescue Errno::ENOENT => e logger.warn e.message @@ -23,7 +24,7 @@ module SMSd @running_since = DateTime.now catch_signals - Process.daemon if options[:daemonize] + Process.daemon(false, !@options[:output].nil?) if options[:daemonize] loop do pong if options[:alive] @@ -60,6 +61,14 @@ module SMSd end end + def redirect_output + if @options[:output] + output_file = File.new(@options[:output], 'a') + $stdout.reopen(output_file) + $stderr.reopen(output_file) + end + end + def catch_signals signal_term = proc { @terminate = true } Signal.trap('SIGTERM', signal_term) diff --git a/lib/smsd/cli/options.rb b/lib/smsd/cli/options.rb index 2feca5f..ee90e08 100644 --- a/lib/smsd/cli/options.rb +++ b/lib/smsd/cli/options.rb @@ -34,6 +34,11 @@ module SMSd options[:pin] = pin end + opts.on('-r', '--redirect-output FILE', + 'Redirect stdout and stderr to a file') do |output| + options[:output] = output + end + opts.separator '' opts.separator 'Common options:'