BUU has asked for the wisdom of the Perl Monks concerning the following question:

As the title indicates, I'm trying to solve a fairly basic problem. I'm dealing with a function that prints to STDOUT at a 'C' level, which means that stuff like perlio, in memory filehandles, localized globs and such don't work. So I decided on tempfiles. I would create the tempfile, redirect STDOUT, call my C function, it writes to the tempfile, I close STDOUT, open it again appropiately and read from the tempfile. Everything will be peachy keen! Unfortunately I'm getting a fairly strange error. When I close the redirected STDOUT, it empties the tempfile! Here's the code:
my $old_stdout; my( $fh, $fn ); sub redir_stdout { open $old_stdout,">&STDOUT" or die "Couldn't open old_out to &STDOUT + $!"; ( $fh, $fn ) = tempfile(); print "tempfile: $fn\n"; open STDOUT, '>&=', $fh or die "Couldn't open STDOUT to tmpfile $fn: + $!"; } sub undir_stdout { close STDOUT; close $fh; open STDOUT, ">&=", $old_stdout or die "Couldn't reopen STDOUT to ol +d_out: $!"; open $fh, "<$fn" or die "Couldn't open temp file, $fn : $!"; if(wantarray) { return <$fh>; } else { local $/; return <$fh>; } }
I use it like so:
redir_stdout(); stupid_c_function(); die undir_stdout();
Which of course returns nothing. When I print the filename of the tempfile and comment out undir_stdout, I can examine the tempfile after the script exits and find that it contains all of the expected data. I played with comments in the undir_stdout function and it seems to be the 'close STDOUT' line specifically that clears the file. (The reason these things are actual functions is a tad complicated, mostly having to do with perl code that generates perlcode).

Update:

I drastically simplified my code, so now it looks like:
open my $old_out, ">&STDOUT" or die $!; open STDOUT, "> sc_out" or die $!; send_command('i', "@_", 0 ); #close STDOUT;
That works, in that ./sc_out contains the expected output when the script terminates. If I uncomment "close STDOUT", sc_out is empty.

Update the second:

Solved the problem. It turns out the C code in send_command was buffering the output, so when I closed STDOUT, the buffer couldn't flush to the file when the script terminated. Adding a fflush makes it all work nicely.