简体   繁体   English

IPC :: Open3遇到问题

[英]Trouble with IPC::Open3

I am writing a simple script using IPC::Open3. 我正在使用IPC :: Open3编写一个简单的脚本。 The script produces no output to either stdout or stderr, while I would expect output to both. 该脚本不会向stdout或stderr产生任何输出,而我希望两者都输出。

The complete source code: 完整的源代码:

#!/usr/bin/env perl 

use strict;
use warnings;
use utf8;

use IPC::Open3;

pipe my $input, my $output or die $!;
my $pid =  open3(\*STDIN, $output, \*STDERR, 'dd', 'if=/usr/include/unistd.h') or die $!;

while(<$input>) {
    print $_."\n";
}
waitpid $pid, 0;

I am fairly certain that I am using IPC::Open3 incorrectly. 我可以肯定我使用的IPC :: Open3错误。 However, I am still confused as to what I should be doing. 不过,我仍然困惑,我应该做的。

It's the pipe . pipe Without knowing why it's there I can't say more. 不知道为什么会在那里,我不能说更多。 This works fine. 这很好。

my $reader;
my $pid =  open3(\*STDIN, $reader, \*STDERR, 'dd', 'if=/usr/include/unistd.h') or die $!;

while(<$reader>) {
    print $_."\n";
}
waitpid $pid, 0;

I realize it's probably just an example, but in case it's not... this is complete overkill for what you're doing. 我意识到这可能只是一个例子,但万一不是……这完全是您正在做的事。 You can accomplish that with backticks. 您可以使用反引号来实现。

print `dd if=/usr/include/unistd.h`

IPC::Open3 is a bit overcomplicated. IPC :: Open3有点复杂。 There are better modules such as IPC::Run and IPC::Run3 . 有更好的模块,例如IPC :: RunIPC :: Run3

use strict;
use warnings;

use IPC::Run3;

run3(['perl', '-e', 'warn "Warning!"; print "Normal\n";'],
     \*STDIN, \*STDOUT, \*STDERR
);

Your program suffers from the following problems: 您的程序存在以下问题:

  • \\*STDIN (open STDIN as a pipe tied to the child's STDIN ) should be <&STDIN (use the parent's STDIN as the child's STDIN ). \\*STDIN (打开的STDIN作为连接到孩子的STDIN的管道)应为<&STDIN (使用父母的STDIN作为孩子的STDIN )。
  • \\*STDERR (open STDERR as a pipe tied to the child's STDERR ) should be >&STDERR (use the parent's STDERR as the child's STDERR ). \\*STDERR (将STDERR作为连接到孩子的STDERR的管道打开)应为>&STDERR (将父级的STDERR用作孩子的STDERR )。
  • The value you place in $output is being ignored and overwritten. 您放置在$output的值将被忽略和覆盖。 Fortunately, it's being overwritten with a correct value! 幸运的是,它被正确的值覆盖!
  • You use print $_."\\n"; 您使用print $_."\\n"; , but $_ is already newline-terminated. ,但$_已经以换行符结尾。 Either chomp first, or don't add a newline. 要么先chomp ,要么不添加换行符。
  • open3 isn't a system call, so it doesn't set $! open3不是系统调用,因此不会设置$! .
  • open3 doesn't return false on error; open3不会在错误时返回false; it throws an exception. 它会引发异常。

So we get something like: 因此,我们得到如下信息:

#!/usr/bin/env perl

use strict;
use warnings;
use feature qw( say );

use IPC::Open3;

my $pid = open3('<&STDIN', my $output, '>&STDERR',
    'dd', 'if=/usr/include/unistd.h');

while (<$output>) {
    chomp;
    say "<$_>";
}

waitpid($pid, 0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM