On 10/23/07, monk <[EMAIL PROTECTED]> wrote:
> I'm having problems accessing a variable outside its subroutine.
> I've tried several combinations too long to write here. Maybe I just
> can't see the forest for the trees. But I'm lost. I need your
> wisdom.
>
> I'd like my program below to change $status to zero to exit the loop.
>
> meaning...$> perl test.pl --start
> it prints out indefinitely "hello world"
>
> But if $> perl test.pl --stop
> it gets out of the loop exiting the program.
>
>
Hi,
When script is running,how can you re-run it with another argument to
make it stop?
The general way to let a running program stop is to send a signal.
Let me modify your code to,
use strict;
use warnings;
our $status = 1;
$SIG{TERM} = $SIG{INT} = sub {$status = 0};
start();
sub start {
while ($status){
print "hello world!\n";
sleep 1;
}
print "out of loop. Will exit now\n";
exit 0;
}
__END__
When you run it,you can send SIGINT or SIGTERM to let it exit gracefully.
Given the process id is 1234,under unix you can say,
$ kill -s 2 1234
The script would print "out of loop. Will exit now" and exit.
(-s 2 means sending SIGINT,see `man 7 signal` for details).
The most important change for the code above is that we re-defined
singal handlers:
$SIG{TERM} = $SIG{INT} = sub {$status = 0};
When the script receive SIGTERM or SIGINT,it set the global $status to
0,so the loop condition become false,the program exit.
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/