#!/usr/bin/perl use strict; use warnings; use IO::Select qw( ); use IPC::Open3 qw( open3 ); use Symbol qw( gensym ); my @cmd = ( 'perl', '-e', <<__EOI__ use IO::Handle qw( ); # Usually want autoflush=1 for pipes. STDOUT->autoflush(0); STDERR->autoflush(0); print STDERR ('a') for 1..10000; STDERR->flush(); print STDOUT ('b') for 1..10000; STDOUT->flush(); print STDERR ('c') for 1..10000; STDERR->flush(); print STDOUT ('d') for 1..10000; STDOUT->flush(); __EOI__ ); { my ($to_child, $fr_child, $fr_child_err) = map gensym, 1..3; my $pid = open3($to_child, $fr_child, $fr_child_err, @cmd); my $sel = IO::Select->new(); $sel->add($fr_child); $sel->add($fr_child_err); while (my @ready = $sel->can_read()) { foreach my $handle (@ready) { if ($handle == $fr_child) { my $bytes_read = sysread($handle, my $buf='', 1024); if ($bytes_read == -1) { warn("Error reading from child's STDOUT: $!\n"); $sel->remove($handle); next; } if ($bytes_read == 0) { print("Child's STDOUT closed\n"); $sel->remove($handle); next; } printf("%4d bytes read from child's STDOUT\n", $bytes_read); } elsif ($handle == $fr_child_err) { my $bytes_read = sysread($handle, my $buf='', 1024); if ($bytes_read == -1) { warn("Error reading from child's STDERR: $!\n"); $sel->remove($handle); next; } if ($bytes_read == 0) { print("Child's STDERR closed\n"); $sel->remove($handle); next; } printf("%4d bytes read from child's STDERR\n", $bytes_read); } } # For demonstration purposes only. # Should cause some STDOUT and STDERR reads to become interlaced use Time::HiRes qw( sleep ); sleep(0.1); } for (;;) { my $pid = wait(); last if $pid == -1; # Check the error code of the child process if desired. } }