[sf-perl] not understanding program behavior with alarm()

Greg Lindahl greg at blekko.com
Sat Feb 4 21:17:14 PST 2012


Yes, you need to fork first.

sub system_with_timeout
{
    my ( $timeout, @argv ) = @_;
    my $status = 1;
    return 1 unless defined $timeout and $timeout > 0;
    return 1 unless @argv and "@argv";

    my $pid = fork;
    if ( ! defined $pid ) { die "fork failed: $!"; }
    if ( $pid ) # parent                                                                                                                     
    {
        local $SIG{ALRM} = sub { die "Alarm fired\n"; };
        alarm $timeout;
        eval {
            waitpid $pid, 0;
            $status = $?;
        };
        if ( $@ ) # alarm fired                                                                                                              
        {
            kill 9, $pid;
            return $status || 1; # force it to non-zero                                                                                      
        }
        alarm 0;
    }
    else
    {
        exec @argv;
        die "exec failed: $!";
    }
    return $status;
}


On Fri, Feb 03, 2012 at 04:08:36PM -0800, David Alban wrote:
> hmmm...  then i should probably fork() first... ?
> 
> On Fri, Feb 3, 2012 at 2:57 PM, Francisco Obispo <fobispo at isc.org> wrote:
> > Perl's system() call performs a fork() on the specified process,
> >
> > you might want to try exec() instead..
> 
> -- 
> Live in a world of your own, but always welcome visitors.
> ***
> Rule of law is for the little people.
> http://www.amazon.com/Liberty-Justice-Some-Equality-Powerful/dp/0805092056
> _______________________________________________
> SanFrancisco-pm mailing list
> SanFrancisco-pm at pm.org
> http://mail.pm.org/mailman/listinfo/sanfrancisco-pm


More information about the SanFrancisco-pm mailing list