Perl of wisdom

Catching Signals

A often misunderstood command on Unix platforms is the kill command. The kill command sends a signal to a program, and one of the popular uses of kill is to send the -9 (SIGKILL) signal to a process, effectively "killing" that process.

You can get a list of signals by using the -l switch.

Perl sample code

Have a look at the following sample code:

1 #!/usr/bin/perl
3 # sample signal handler
5 # define a global variable
6 my $globalint = 0;
8 # install the signal handler
9 $SIG{HUP} = \&sighHUP;
11 print "The PID for this script is '$$'\n";
12 while( 1 ){
14 $globalint++;
15 sleep(1);
17 }
19 sub sighHUP {
21 $SIG{HUP} = \&sighHUP;
23 # print the value of
24 # $globalint and reset
25 # to 0
26 print "\n\nglobalint=$globalint\n\n";
27 $globalint = 0;
28 return 1;
30 }

In this little script we start off by defining our signal handler (line 9). The signal handler calls a subroutine, defined in lines 19-30. Note that on line 21 we redefine the signal handler - this is not always a requirement, but I do it out of habit.

The main function of the script is to increment an integer every second (lines 12-17). When a SIGHUP (signal 1) is caught, the integer is reset and counting starts again.

To run and test this script you would need two open terminals. On terminal 1, run the script. On startup, the script will print its own PID (process ID). On terminal 2, wait a couple of seconds and send the 'kill -1 ' command. On terminal 1 you should see the value of the integer, and then it would be reset. Wait a couple of seconds and do it again.

To stop the process you can just press CTRL+C on terminal 1, or on terminal 2 send the 'kill -9 ' command.

Next time...

That's it for this week. Next week I will show how to use this and the previous weeks wisdom to make the basics of a dynamic code environment.

Have fun!

Today's Perl Link

Perl modules can save a lot of time and changes are very good that some body somewhere already coded a module to solve a problem you face. The ultimate source for Perl Modules is CPAN.


Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?