在Perl中等价于< nul 2>& 1(来自Batch)?

时间:2013-02-27 13:02:30

标签: perl batch-file cygwin io-redirection

我在Windows XP上使用Cygwin Perl。

Perl中是否有等效的>nul 2>&1批处理?

请参阅Here

3 个答案:

答案 0 :(得分:3)

如果你有一个shell命令:

system("$cmd >nul 2>&1");
die $! if $? < 0;
die "Child killed by signal ".($? & 0x7F)."\n" if $? & 0x7F;
die "Child exited with error ".($? >> 8)."\n" if $? >> 8;

如果你有一个程序和args:

use IPC::Open3 qw( open3 );

open(local *CHILD_STDIN,  '<', 'nul') or die $!;
open(local *CHILD_STDOUT, '>', 'nul') or die $!;
my $pid = open3(
   '<&CHILD_STDIN',
   '>&CHILD_STDOUT',
   undef,  # 2>&1
   $prog, @args,
);
waitpid($pid, 0);
die $! if $? < 0;
die "Child killed by signal ".($? & 0x7F)."\n" if $? & 0x7F;
die "Child exited with error ".($? >> 8)."\n" if $? >> 8;

注意:如果在启动孩子时出错,则死亡。

答案 1 :(得分:1)

Cygwin的工作方式与Unix类似,其中空设备的名称为/dev/null,而不是nul。运行外部命令并压制所有输出

system("mycommand arg1 arg2 >/dev/null 2>&1") == 0
    or warn "$0: mycommand exited $?";

要绕过shell解析,您是否还必须自己执行重定向。

use POSIX '_exit';  # if not available, fall back to plain exit with caveats

my $pid = fork;
die "$0: fork: $!" unless defined $pid;

if ($pid) {
    if (waitpid $pid, 0 >= 0) {
        my $status = $? >> 8;
        if ($status == 13) {
            warn "$0: error starting mycommand";
        }
        else {
            warn "$0: mycommand exited $status";
        }
    }
    else {
        warn "$0: waitpid: $!";
    }
}
else {
    open STDOUT, ">",  "/dev/null"   or warn("$0: open: $!"), _exit 13;
    open STDERR, ">&", \*STDOUT      or                       _exit 13;
    exec "mycommand", "arg1", "arg2" or                       _exit 13;
}

答案 2 :(得分:0)

正如我在回答你previous question时写的那样,你想要的是

system('cmd /C', $exe, @parm, '1>nul', '2>nul');