LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Perl:Suicide if take long (https://www.linuxquestions.org/questions/programming-9/perl-suicide-if-take-long-842283/)

smc2 11-04-2010 05:04 AM

Perl:Suicide if take long
 
Hi..
Do you have any idea how I may kill my own Perl script if it is running for more than threshold minutes?



Thanks.

Dark_Helmet 11-04-2010 05:23 AM

Does the system you're using have the at command? If so, have your Perl script execute an appropriate "at" command immediately after the script starts. You use "at" to launch a another script that kills the original Perl script if it's still running after X minutes/hours/days.

smc2 11-04-2010 06:00 AM

Dear Dark_Helmet,

I use cronetab to run my script every minute, therefore
I want to be sure that it is closed after for example 30 second so that at each minutes just one instance of the script is running..

Thanks for your attention.

catkin 11-04-2010 08:56 AM

How about a bash wrapper script?
Code:

#!/bin/bash

/path-to-perl-script &
sleep 30
kill <signal as required> $!


smc2 11-05-2010 04:12 AM

Wise and nice script, for sure it may help, but do you have any idea how to do it within shell script that makes the script be killed independent of OS it is running on?

Thanks..

catkin 11-05-2010 04:13 AM

Sorry -- I don't perl

EDIT:

But surely perl can do it -- it's a powerful language. In case it helps, I'd do it like this in bash
Code:

#!/bin/bash

( sleep 30 ; kill <appropriate signal> $$ )&

<rest of script>

The concept is to start a backgrounded sub-process that will kill the parent process after 30 seconds. I'm not certain without experimenting whether the background process will be killed when the parent exits; it might be necessary for the parent to kill the sub-process before it itself exits (which would require the excellent programming discipline of a single function to do the exit :)).

Sergei Steshenko 11-05-2010 05:16 AM

Why shouldn't the Perl script in question just kill itself ?

For that you can use threads.

I.e. use threads (or forks; threads work on any system), create a thread which just waits for the given timeout to expire, and when it expires, it calls built-in Perl 'kill' function (see perldoc -f kill) with PID of the script (the $$ variable).

The other thread will be the script proper itself, i.e. it will do the useful job.

Read about threads here: http://perldoc.perl.org/threads.html .

And about forks: http://search.cpan.org/~rybskej/forks-0.34/lib/forks.pm .

If you want cross-platform, as I said, you need threads and not forks.


All times are GMT -5. The time now is 02:42 PM.