Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Temporarily Redirect STDOUT to /dev/null - Not Working All The Time

I am using

Server version: Apache/1.3.34 (Debian)
mod_perl - 1.29

By refering to STDIN, STDOUT, and STDERR Streams

#!/usr/bin/perl5
package main;

use strict 'vars';

{
    # Our mighty holy legacy code love to print out message in the middle of operation. Shihh....
    # Let's quietly redirect those message to /dev/null.
    my $nullfh = Apache::gensym( );
    open $nullfh, '>/dev/null' or warn "Can't open /dev/null: $!";
    local *STDOUT = $nullfh;
    print "BYE BYE WORLD";    # Shouldn't show in webpage.
    close $nullfh;
}

print "X BEGIN HELLO WORLD";  # Should show in webpage.

I realize that it is not working all the time. For example, I refresh the page for 10 times. x times it will print out "X BEGIN HELLO WORLD". (10-x) time it just print out nothing.

I cannot find any reason why it behave this way. May I know anyone of you encounter similar problem as me?

like image 383
Cheok Yan Cheng Avatar asked Dec 30 '22 21:12

Cheok Yan Cheng


2 Answers

I need to explicitly store and restore. It works for my case. But I am not sure why.

# Take copies of the file descriptors
open OLDOUT, '>&STDOUT';
my $returned_values = 0;
{
    # Our mighty holy legacy code love to print out message in the middle of operation. Shihh....
    # Let's quietly redirect those message to /dev/null.
    local *STDOUT;
    open STDOUT, '>/dev/null' or warn "Can't open /dev/null: $!";
    print "BYE BYE WORLD";    # Shouldn't show in webpage.
    close STDOUT;
}
# Restore stdout.
open STDOUT, '>&OLDOUT' or die "Can't restore stdout: $!";
# Avoid leaks by closing the independent copies.
close OLDOUT or die "Can't close OLDOUT: $!";
like image 85
Cheok Yan Cheng Avatar answered Apr 28 '23 04:04

Cheok Yan Cheng


Try:

local $|=1;

before print. This bypass the buffering.

See http://perldoc.perl.org/perlvar.html#HANDLE-%3Eautoflush%28EXPR%29

like image 21
J-16 SDiZ Avatar answered Apr 28 '23 06:04

J-16 SDiZ