How to enforce a definite timeout in perl?

房东的猫 提交于 2019-11-29 11:27:14
simbabque

I've faced a similar issue before in https://stackoverflow.com/a/10318268/1331451.

What you need to do is add a $SIG{ALRM} handler and use alarm to call it. You set the alarm before you do the call and cancel it directly afterwards. Then you can look at the HTTP::Result you get back.

The alarm will trigger the signal, and Perl will call the signal handler. In it, you can either do stuff directly and die or just die. The eval is for the die no to break the whole program. If the signal handler is called, the alarm is reset automatically.

You could also add different die messages to the handler and differentiate later on with $@ like @larsen said in his answer.

Here's an example:

my $ua = LWP::UserAgent->new;
my $req = HTTP::Request->new;
my $res;
eval {
  # custom timeout (strace shows EAGAIN)
  # see https://stackoverflow.com/a/10318268/1331451
  local $SIG{ALRM} = sub {
    # This is where it dies
    die "Timeout occured...";
  }; # NB: \n required
  alarm 10;
  $res = $ua->request($req);
  alarm 0;
};
if ($res && $res->is_success) {
  # the result was a success
}

In general, you can use an eval block if you want to trap and control sections of code that may die.

while( … ) { # this is your main loop
    eval {
        # here the code that can die
    };
    if ($@) {
        # if something goes wrong, the special variable $@ 
        # contains the error message (as a string or as a blessed reference,
        # it depends on how the invoked code threats the exception.
    }
}

You can find further info in the documentation for the eval function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!