...but one way is to capture the process ID from the shell:
$pid = `command && echo $$` ;
This wouldn't work.
First (and least relevant), backticks interpolate the $$, so you'd get the PID of the Perl process here. But even when fixing this using \$\$, you'd still not get the PID of the command, but that of the shell. And killing the shell does not necessarily also kill the command. You could in theory try to fix the latter problems by using exec, i.e.
$pid = `echo \$\$ && exec command` ;
However, that still wouldn't work, because you wouldn't get at the $pid before the entire backticks command completed. And in case of a timeout (where you would need the PID primarily), you'd get nothing at all:
#!/usr/bin/perl -w
use strict;
my $pid;
local $SIG{ALRM} = sub {
die "Timeout (pid=$pid)\n";
};
my $command = "perl -e '<>'";
alarm 5;
eval {
$pid = `echo \$\$ && exec $command`;
};
print $@;
alarm 0;
print "pid=$pid\n";
__END__
Use of uninitialized value $pid in concatenation (.) or string at ./96
+0632.pl line 7.
Timeout (pid=)
Use of uninitialized value $pid in concatenation (.) or string at ./96
+0632.pl line 18.
pid=
P.S.: contrary to what is implied elsewhere in the thread, alarm does by default not kill the subprocess behind the backticks in case of a timeout — as can easily be verified using ps.