#!/usr/bin/env ruby # -*- encoding: binary -*- # An example of using IO.tee, this is a limited version of the standard # "tee" utility that requires stdin and stdout to both be pipes. require 'io/splice' usage = "filter_prog1 | #$0 DEST | filter_prog2" dest = ARGV.shift or abort usage $stdin.stat.pipe? or abort "stdin must be a pipe" $stdout.stat.pipe? or abort "stdout must be a pipe" dest = File.open(dest, 'wb') out_fd = dest.fileno stdin_fd = $stdin.fileno stdout_fd = $stdout.fileno begin nread = begin # "copy" data from stdin to stdout, without consuming stdin IO.tee(stdin_fd, stdout_fd, IO::Splice::PIPE_CAPA, 0) rescue EOFError break end # sends data to the file, consumes stdin nwritten = IO.splice(stdin_fd, nil, out_fd, nil, nread, 0) nwritten == nread or abort "short splice to file: #{nwritten} != #{nread}" end while true