【问题标题】:Why is Perl's $? returning the wrong value for the exit code of a forked process?为什么是 Perl 的 $?为分叉进程的退出代码返回错误的值?
【发布时间】:2011-02-23 22:32:44
【问题描述】:

考虑这个在 Perl 中 fork()ing 然后等待孩子死去的简单例子:

#!/usr/bin/perl

use strict;
use warnings;

if (fork() == 0) {
        exit(1);
}

waitpid(-1,0);

print $?;

在 Solaris 10 上运行脚本我得到以下结果:

$ perl test.pl
256

我怀疑 的值正在向上移动,因为当我在孩子中执行 exit(2) 时,输出变为 512

我似乎无法在 perl 的 waitpid 中找到此文档。这是我系统上的错误还是我做错了什么?

【问题讨论】:

    标签: perl waitpid


    【解决方案1】:

    它记录在perlvar 手册页的$? 部分。

    即真正的退出代码是$? >> 8

    【讨论】:

    【解决方案2】:

    孩子甚至可能没有机会打电话给exit。因此,$? 包含的信息不仅仅是exit 参数。

    if    ( $? == -1  ) { die "Can't launch child: $!\n"; }
    elsif ( $? & 0x7F ) { die "Child killed by signal ".( $? & 0x7F )."\n"; }
    elsif ( $? >> 8   ) { die "Child exited with error ".( $? >> 8 )."\n"; }
    else                { print "Child executed successfully\n"; }
    

    system 的文档中更清楚地记录了这一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-12
      • 1970-01-01
      • 2016-03-10
      • 2016-02-16
      • 1970-01-01
      • 2013-01-14
      • 2011-02-13
      • 2023-03-27
      相关资源
      最近更新 更多