cmv has asked for the wisdom of the Perl Monks concerning the following question:

I seem to have found a way to get $? to always return -1 (even on the date command)! What's up with this?

Try this test program on *nix and see if it happens to you too...

my $ret1 = `date`; my $exit1 = $?; print STDERR "exit1=$exit1 ret1=$ret1"; my $pid; if($pid = fork) { $SIG{CHLD} = sub {wait}; print STDERR "$$: parent pid=$pid\n"; }elsif (defined $pid) { print STDERR "$$: child\n"; setpgrp(0, $$); exec "exec sleep 500 &" || die "Bad exec $!"; exit; } foreach my $i (1..5) { my $ret2 = `date`; my $exit2 = $?; print STDERR "exit2=$exit2 ret2=$ret2"; }

Replies are listed 'Best First'.
Re: $? stuck returning -1...
by jettero (Monsignor) on Jun 20, 2007 at 15:52 UTC
    The back ticks don't set $? (see perlop). That is the correct behavior. If you want the return value, look at system() instead. It turns out that I'm wrong about that. According to perlvar it is indeed supposed to set $?, but it's not the return value, it's more.

    $exit = $? >> 8 and $sig = $? & 128...

    -Paul

      Paul-

      I'm confused. If it is supposed to set $?, then doesn't the sample program show that it's not working? My output looks like this:

      exit1=0 ret1=Wed Jun 20 15:09:04 CDT 2007 24862: parent pid=24864 24864: child exit2=-1 ret2=Wed Jun 20 15:09:04 CDT 2007 exit2=-1 ret2=Wed Jun 20 15:09:04 CDT 2007 exit2=-1 ret2=Wed Jun 20 15:09:04 CDT 2007 exit2=-1 ret2=Wed Jun 20 15:09:04 CDT 2007 exit2=-1 ret2=Wed Jun 20 15:09:04 CDT 2007
      Thanks -Craig
        You're setting $SIG{CHLD} yourself so the wait() implicit in the backticks command will report there are no children.

        Set $SIG{CHLD} to undef before the foreach loop to see that that fixes the problem.

        update:

        $|=1; my $ret1 = `date`; my $exit1 = $?; print STDERR "exit1=$exit1 ret1=$ret1"; $SIG{CHLD} = sub {print "Sigchld\n";wait}; foreach my $i (1..5) { my $ret2 = `date`; my $exit2 = $?; print STDERR "exit2=$exit2 ret2=$ret2"; }
        output:
        exit1=0 ret1=Wed Jun 20 22:29:13 CEST 2007 Sigchld exit2=-1 ret2=Wed Jun 20 22:29:13 CEST 2007 Sigchld exit2=-1 ret2=Wed Jun 20 22:29:13 CEST 2007 Sigchld exit2=-1 ret2=Wed Jun 20 22:29:13 CEST 2007 Sigchld exit2=-1 ret2=Wed Jun 20 22:29:13 CEST 2007 Sigchld exit2=-1 ret2=Wed Jun 20 22:29:13 CEST 2007
Re: $? stuck returning -1...
by ikegami (Patriarch) on Jun 20, 2007 at 16:31 UTC

    $? == -1 means the system call to launch the command failed. The error code/msg is in $!.

      If this were true, then I shouldn't be getting a valid date output, but I am.

      This is the confusing part. Why am I getting $?=-1 after the backtick command works just fine?

      Aaaahhh, joost: explains all. Thanks!