Created
July 24, 2015 12:20
-
-
Save meson10/56831de08a9af74d3f7c to your computer and use it in GitHub Desktop.
Hijack stdout and stderr for forks
This file contains 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
require 'logger' | |
require 'stringio' | |
def capture_output | |
old_stderr, $stderr = $stderr, StringIO.new | |
old_stdout, $stdout = $stdout, StringIO.new | |
yield | |
[$stderr.string, $stdout.string] | |
ensure | |
$stderr = old_stderr | |
$stdout = old_stdout | |
end | |
class Request | |
def make_logger | |
lg = Logger.new(STDERR) | |
lg.level = Logger::DEBUG | |
lg | |
end | |
def initialize(ident) | |
@ident = ident | |
@logger = make_logger | |
original_formatter = Logger::Formatter.new | |
@logger.formatter = proc do |severity, datetime, progname, msg| | |
original_formatter.call(severity, datetime, @ident, msg.dump) | |
end | |
end | |
def func_in_fork | |
3.times do |i| | |
puts "Regular puts message #{i}" | |
$stdout.puts "#{i} on stdout" | |
$stderr.puts "#{i} on stderr" | |
end | |
end | |
def process | |
stderr, stdout= capture_output do | |
func_in_fork | |
end | |
stderr.each_line do |line| | |
@logger.debug line | |
end | |
stdout.each_line do |line| | |
@logger.debug line | |
end | |
end | |
end | |
pids = [] | |
3.times do |i| | |
r = Request.new(i) | |
pids << Process.fork do | |
sleep 0.5 | |
r.process | |
end | |
end | |
pids.each do |pid| | |
Thread.new do | |
Process.waitpid(pid) | |
end.join | |
end | |
puts "Regular done on stdout!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment