-5

How can I launch and end a process after a time out in perl? I need the script to work in Windows and Unix, what's my best options?

edit: how do I get the process ID for the started process on windows and unix and how do I kill it at the timeout

user391986
  • 29,536
  • 39
  • 126
  • 205
  • Maybe you should be more specific. What exactly are you trying to do and where do you have problems in understanding the problem or achieving what you need? – matthias krull Feb 20 '12 at 21:48
  • It seems to me like the user is just trying to prevent their code from running too long. – GoldenNewby Feb 20 '12 at 21:49
  • 1
    From the [official Perl FAQ](http://faq.perl.org): [How do I timeout a slow event?](http://learn.perl.org/faq/perlfaq8.html#How-do-I-timeout-a-slow-event-) – daxim Feb 20 '12 at 22:15
  • I decided to figure out in the script what OS it's running on and implement different handling for each. On windows I got Win32::Process working amazingly well. On Unix I'm using open. – user391986 Feb 21 '12 at 05:56

1 Answers1

1

You can use the operating system to signal an ALRM (alarm), which you can then exit your process on after a set number of seconds.

So for instance, if at the top of your script you put:

alarm 300;

This will cause your process to receive an ALRM signal. This will kill your process immediately, or you can trap it and clean up your process before it dies.

For further reading: http://perldoc.perl.org/functions/alarm.html

You can trap the signal like this:

$SIG{ALRM} = sub {

# Clean up process here and exit

};

In response to your edit "edit: how do I get the process ID for the started process on windows and unix and how do I kill it at the timeout"

The process ID is stored in perl as $$, so:

print 'My process ID is:', $$, "\n";
GoldenNewby
  • 4,382
  • 8
  • 33
  • 44
  • Just be aware that there are limits for "alarm" on Windows: you cannot interrupt your script (see [perlport](http://perldoc.perl.org/perlport.html#Alphabetical-Listing-of-Perl-Functions)) if on a system call (ie waiting on a socket or something similar). – Ouki Feb 20 '12 at 22:03
  • My background is more in linux, but wouldn't that process also be a zombie process in that situation (ie: not killable by conventional methods)? – GoldenNewby Feb 20 '12 at 22:05
  • We talking Windows here. So no zombie process ;) Your perl will simply not get your signal as being on the "system". – Ouki Feb 20 '12 at 22:30