initial
[ruby_io_splice.git] / examples / splice-tee.rb
blobd8479c4093a863f4d663512fcc55687a1b070476
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')
14 out_fd = dest.fileno
16 stdin_fd = $stdin.fileno
17 stdout_fd = $stdout.fileno
19 begin
20   nread = begin
21     # "copy" data from stdin to stdout, without consuming stdin
22     IO.tee(stdin_fd, stdout_fd, IO::Splice::PIPE_CAPA, 0)
23   rescue EOFError
24     break
25   end
27   # sends data to the file, consumes stdin
28   nwritten = IO.splice(stdin_fd, nil, out_fd, nil, nread, 0)
30   nwritten == nread or
31     abort "short splice to file: #{nwritten} != #{nread}"
32 end while true