Domanda

Come potrei implementare in questo pezzo di codice un timeout: se il "hwinfo --usb" -command non ha prodotto nulla dopo un certo periodo di tempo, (fermata il comando e) fare un ritorno o morire dal sub _usb_device.

#!/usr/bin/env perl
use warnings; 
use strict;


sub _usb_device {
    my @array;
    {
    local $/ = "";
    @array = qx( hwinfo --usb );
    }
    ...
    ...
}
È stato utile?

Soluzione

Timeout si realizza con allarmi .


 sub _usb_device 
 {
    # Scope array
    my @array;

    # Try shell command
    eval
    {
        local $SIG{ALRM} = sub { die "timeout\n" };
        local $/ = "";
        alarm 10;
        @array = qx( hwinfo --usb );
        alarm 0;
    };

    # Catch and rethrow non timout errors
    die $@ if $@ && $@ ne "timeout\n";

    # Done
    return @array;
 }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top