---
title: "Time out script in perl"
author: "Ashton"
date: "2008-03-13T13:06:30Z"
tags: []
slug: "time-out-script-in-perl"
draft: false
lastmod: "2008-03-13T13:06:30Z"
id: 170793
url: "https://ashton.iteye.com/blog/170793"
---

I have a script used to test the sftp connection which runs too long, so I want to time it out after a given number of seconds.After a google search and perl doc reading, I find the ALARM function can work well.

#!/usr/bin/perl
eval {
   local %SIG;//in some ENV %SIG should be global variable
   $SIG{ALRM}= sub{ die "timeout reached, after 20 seconds!\n"; };
   alarm 20;
   print "sleeping for 60 seconds\n";
   sleep 60; # This is where to put your code, between the alarms
   alarm 0;
};

alarm 0;

if($@) { print "Error: $@\n"; }

exit(0);

reference:http://perl.coding-school.com/perl-timeout/