gpt4 book ai didi

perl - IO::Pipe - close() 没有设置 $?

转载 作者:行者123 更新时间:2023-12-04 04:36:32 28 4
gpt4 key购买 nike

我的理解是关闭 IO::Pipe 的句柄对象应该使用方法( $fh->close )而不是内置( close($fh) )来完成。

前几天,我出于习惯在 IO::Pipe 上犯了错误并使用内置对我预期会失败的命令打开的对象。我很惊讶$?是零,我的错误检查没有被触发。

我意识到我的错误。如果我使用内置的,IO:Pipe无法执行 waitpid()并且无法设置 $? .但令我惊讶的是 perl 似乎仍然在不设置 $? 的情况下关闭管道通过核心。

我编写了一个小测试脚本来说明我的意思:

use 5.012;
use warnings;

use IO::Pipe;

say 'init pipes:';
pipes();
my $fh = IO::Pipe->reader(q(false));
say 'post open pipes:';
pipes();

say 'return: ' . $fh->close;
#say 'return: ' . close($fh);
say 'status: ' . $?;
say q();

say 'post close pipes:';
pipes();

sub pipes
{
for my $fd ( glob("/proc/self/fd/*") )
{
say readlink($fd) if -p $fd;
}
say q();
}

使用该方法时,它显示管道在关闭后消失, $?设置如我所料:
init pipes:

post open pipes:
pipe:[992006]

return: 1
status: 256

post close pipes:

而且,当使用内置时,它也似乎关闭了管道,但没有设置 $? :
init pipes:

post open pipes:
pipe:[952618]

return: 1
status: 0

post close pipes:

我觉得奇怪的是内置的结果是管道关闭,但没有设置 $? .任何人都可以帮助解释差异吗?

谢谢!

最佳答案

如果您查看 IO::Handle 的代码(其中 IO::Pipe::End 是一个子类),您将看到以下内容:

sub close {
@_ == 1 or croak 'usage: $io->close()';
my($io) = @_;

close($io);
}

看起来像 $fh->close只需调用 close $fh .当然,我们不应该在幕后偷看。

我们可以看到 IO::Pipe 之后做一个 close $fh (在幕后),然后它执行一个waitpid:
package IO::Pipe::End;

our(@ISA);

@ISA = qw(IO::Handle);

sub close {
my $fh = shift;
my $r = $fh->SUPER::close(@_); # <-- This just calls a CORE::close

waitpid(${*$fh}{'io_pipe_pid'},0)
if(defined ${*$fh}{'io_pipe_pid'});

$r;
}

同样有趣的是来自关闭的 Perldoc:

If the filehandle came from a piped open, close returns false if one of the other syscalls involved fails or if its program exits with non-zero status. If the only problem was that the program exited non-zero, $! will be set to 0 .

Closing a pipe also waits for the process executing on the pipe to exit --in case you wish to look at the output of the pipe

afterwards--and implicitly puts the exit status value of that command into $? and ${^CHILD_ERROR_NATIVE} .



这回答了你的问题。

关于perl - IO::Pipe - close(<handle>) 没有设置 $?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19669946/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com