in reply to Pipe, fork, exec and red-hot pokers.

The problem in the end appeared to be that perl expects STDOUT to be a tty (my some_application that I was exec()ing was in fact a perl app ... but I wanted a general solution that didn't need to think about that).

When STDOUT isn't a tty, it turns off line buffering. Hence my requirement to snarf STDOUT in real time was thwarted, until I figured the following out.

This code snipped forks and execs an application, using select to wait for available output on the stderr and stdout for the exec()ed application. The streams are not interleaved.

use IO::Pty; use IO::Select; my $pty = new IO::Pty; pipe($readerr, $writeerr); if (my $pid = fork) { close($writeerr); my $select = new IO::Select; $select->add($pty); $select->add($readerr); while (1) { foreach my $fh ($select->can_read) { my $buf; if (sysread($fh, $buf, 4096)) { print "Read ... $buf ...\n"; } } } } else { close($readerr); $pty->make_slave_controlling_terminal(); my $slave = $pty->slave(); close $pty; $slave->clone_winsize_from(\*STDIN); $slave->set_raw(); open(STDOUT, ">&" . $slave->fileno); open(STDERR, ">&" . $writeerr->fileno); close($slave); exec("/home/hagus/foo.pl"); }
--
Ash OS durbatulk, ash OS gimbatul,
Ash OS thrakatulk, agh burzum-ishi krimpatul!
Uzg-Microsoft-ishi amal fauthut burguuli.

Replies are listed 'Best First'.
Further information
by hagus (Monk) on Apr 09, 2002 at 11:46 UTC
    It turns out that non-line buffering when stdout isn't a tty is standard UNIX practice. So it's not a perl specific wrinkle. Try 'man stdio' on your system (solaris has a particularly detailed page on this).

    So other options might have included using setvbuf under perl (POSIX::setvbuf?) to manually set the stdout descriptor to line buffered. Of course, that would be useless if the first thing that the exec()ed perl program did was test stdout for tty-ishness and revert to non-line buffered ...

    HTH!

    --
    Ash OS durbatulk, ash OS gimbatul,
    Ash OS thrakatulk, agh burzum-ishi krimpatul!
    Uzg-Microsoft-ishi amal fauthut burguuli.