如何在Windows中无视输出缓冲?

时间:2018-01-02 15:37:33

标签: windows perl output-buffering

以下程序生成一个运行windows命令pause的新进程。父母通过管道接收孩子的标准输出并将其打印出来。

但是,在输出换行符之前,pause的输出(Press any key to continue . . .)不会显示。我该如何解决这个问题?

use strict;
use warnings;

use Win32::Job;
use Time::Piece;
use POSIX qw( strftime );

$| = 1;

sub flush_handle {
    my ($fh) = @_;
    while (defined( my $line = <$fh> )) {
        chomp($line);
        print(">> $line\n");
    }
}

my $job = Win32::Job->new;

my $timeout = undef;
my $enable_stdout = 1;

pipe(my $in_pipe, my $out_pipe);
my $pre_term = 0;

my $pid = $job->spawn("cmd", "cmd /C \"pause\"", { stdout => $out_pipe });
close($out_pipe);

my $start_time = time();
my $pid_handler = $job->watch(
    sub {
        my ($h,$m,$s) = (gmtime(time()-$start_time))[2,1,0];
        if ($timeout && $s > $timeout) {
            close($in_pipe);
            $pre_term = 1;
            return 1;
        }

        if (!$enable_stdout) {
            print(sprintf("\r: - Elapsed Time: %02d:%02d:%02d",$h,$m,$s));
        } else {
            flush_handle($in_pipe);
        }

        return 0;           
    }
,1);

0 个答案:

没有答案