io_splice 4.3.0 - cleanups and compatibility fixes
[ruby_io_splice.git] / examples / splice-tee.rb
blob0d40780cf9f4213295251301df553f114c37bbdf
1 #!/usr/bin/env ruby
2 # -*- encoding: binary -*-
4 # An example of using IO.tee, this is a limited version of the standard
5 # "tee" utility that requires stdin and stdout to both be pipes.
6 require 'io/splice'
8 usage = "filter_prog1 | #$0 DEST | filter_prog2"
9 dest = ARGV.shift or abort usage
10 $stdin.stat.pipe? or abort "stdin must be a pipe"
11 $stdout.stat.pipe? or abort "stdout must be a pipe"
13 dest = File.open(dest, 'wb')
15 begin
16   nread = begin
17     # "copy" data from stdin to stdout, without consuming stdin
18     IO.tee($stdin, $stdout, IO::Splice::PIPE_CAPA, 0)
19   rescue EOFError
20     break
21   end
23   # sends data to the file, consumes stdin
24   nwritten = IO.splice($stdin, nil, dest, nil, nread, 0)
26   nwritten == nread or
27     abort "short splice to file: #{nwritten} != #{nread}"
28 end while true