#!/usr/bin/perl

use strict;
use POSIX qw(:errno_h);
use FileHandle;
use Fcntl;

$| = 1;

main: {
        my $command = "tcprobe -i /dev/dvd -T 1 && echo DVDRIP_SUCCESS";
        $command = "echo 'This is a test' && sleep 1 && echo 'This is a test'";

        #--------------------------------------------------------------

        print "-" x 70,"\n";

        print "Execute using qx:\n";

        my $output = qx[($command) 2>&1];
        print $output;

        print "-" x 70,"\n";

        #--------------------------------------------------------------

        print "Execute using pipe with blocking I/O:\n";

        my $pid = open (IN, "( ".$command." ) 2>&1 |")
                or die "can't fork $command";
        while (<IN> ) {
                print "GOT: $_";
        }
        close IN;

        #--------------------------------------------------------------

        print "-" x 70,"\n";

        print "Execute using pipe with non-blocking I/O:\n";

        my $fh = FileHandle->new;
        my $pid = open ($fh, "( ".$command." ) 2>&1 |")
                or die "can't fork $command";

        my $flags = '';
        fcntl($fh, F_GETFL, $flags)
                or die "Can't get flags: $!\n";
        $flags |= O_NONBLOCK;
        fcntl($fh, F_SETFL, $flags)
                or die "Can't set flags: $!\n";

        my $tmp;
        my $buffer;
        while (1) {
                while ( $fh->read ($tmp, 8192) ) {
                        print "GOT: $tmp";
                        $buffer .= $tmp;
                }
                my $finished = $! != EAGAIN;
                last if $finished;
                print "... wait ... ";
                sleep 1;
        }

        close $fh;

	print "\nRESULT: ";
        print "NON-BLOCKING I/O IS BROKEN!!!\n" if $buffer ne $output;
	print "non-blocking I/O works on your system\n" if $buffer eq $output;
}
