3

I am accessing a C function in Ruby through FFI. The function is called AllocTilts::summary.

I want the method to not print anything to STDOUT. However my temporary redirect of STDOUT is not working. Is there something else I can do?

puts 'test outside before' #prints successfully
File.open("/var/alloc_tilts/summary_dump", "w") do |out|
  stdout, $stdout = $stdout, out
  puts 'test inside' #doesn't print to STDOUT as expected
  AllocTilts.summary(2012, 2011) #prints undesired stuff to STDOUT
  $stdout = stdout
end
puts 'test outside after' #prints successfully
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Vanson Samuel
  • 1,953
  • 2
  • 17
  • 30

1 Answers1

1

How do AllocTilts.summary write to stdout? If it uses printf and you do not have access to its source code there is nothing you can do (short of calling libc dup).

The way ruby writes to $stdout rather than the real stdout, is

# from io.c

rb_funcall2(rb_stdout, rb_intern("puts"), argc, argv);

You should use similar code to generate output inside AllocTilts.summary.

gioele
  • 9,748
  • 5
  • 55
  • 80
  • Could you go into more detail about `dup`? – Translunar Mar 06 '14 at 21:21
  • You can play with `dup` to redirect the normal stdout to another file descriptor you created, then redirect from that new file descriptor to Ruby's `$stdout`. You can read about `dup` and stdout redirection at http://stackoverflow.com/questions/2605130/redirecting-exec-output-to-a-buffer-or-file – gioele Mar 13 '14 at 16:38