当打开n个管道到从Perl执行xargs的子进程时,n-1进程接收一个空行

前端之家收集整理的这篇文章主要介绍了当打开n个管道到从Perl执行xargs的子进程时,n-1进程接收一个空行前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
…另一方面,如果我在打开下一个管道之前写了一些东西,这不会发生.

以下代码应该更清楚:

sub test_concurrent_pipes
{
    my $write_at_once = $_[0];
    my $pipe_handle;
    my @pipe_handle_list;
    my $i;
    foreach $i ( 1..3 )
    {
        open ( $pipe_handle,"| xargs echo" ) or die ( "Cannot open pipe.\n" );
        if ( $write_at_once == 1 )
        {
          print $pipe_handle "Hello\n";
        }
        push( @pipe_handle_list,$pipe_handle );
    }
    foreach $pipe_handle ( @pipe_handle_list )
    {
        print $pipe_handle "world\n";
    }
    foreach $pipe_handle ( @pipe_handle_list )
    {
        close ( $pipe_handle );
    }
}

print "Test 0: open all pipes before writing\n";
test_concurrent_pipes(0);

print "Test 1: write Hello before opening next pipe\n";
test_concurrent_pipes(1);

我得到了测试

./test_pipe_2_xargs.pl 
Test 0: open all pipes before writing


world world world
Test 1: write Hello before opening next pipe
Hello
Hello
Hello world world world

正如您在测试0中看到的那样,连续打开3个管道而中间没有任何输出生成2个空行.
奇怪的是,如果我用猫替换xargs echo – 就不会产生空行.
xargs行为似乎也与其手册页相矛盾,该手册页指出标准输入上的空行被忽略.

我该如何避免那些空行呢?

在cygwin / XP上使用Perl 5.14.2,在HP-UX 11.00上使用Perl 5.8.8.

我写了最后我真正想做的事情,因为它与此无关:

通过Perl脚本有效清理所有Clearcase视图中可见的所有派生对象,该脚本在从VOB(rmdo)中删除文件之前,每个视图分配一个进程以删除文件(xargs rm).

解决方法

使用“创建循环”使用局部变量(我的$pipe_handle)可以解决问题.

foreach $i ( 1..3 )
{
    open ( my $pipe_handle,"| xargs echo" ) or die ( "Cannot open pipe.\n" );
    ...
}

猜你在找的Perl相关文章