SiLiK has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,

With your help, I have written a program that reads from a serial port, does some stuff with the input and writes to mysql database in a endless loop. In short it looks something like this:

while ($line = <DEV>) {
  my @values = Parse_Line($pass_some_stuff, $line);
  $sth->execute(@values) || die "Could not transfer data, $!";
}

I am looking for a way of trapping the signal when someone/something trays to "kill -N myProgram.pid" so I wouldn't loose any data ($line), and close up database connections and sio device properly.

10x ahead.

Replies are listed 'Best First'.
Re: shutdown gracefully - kill signal trap
by tachyon (Chancellor) on Sep 24, 2004 at 12:00 UTC

    Just set a signal handler that sets a flag and in the endless loop exit gracefully if it is time....

    my $EXIT = 0; $SIG{INT} = sub{ warn "Caught Zap!\n"; $EXIT = 1 }; while (1) { print "Looping\n"; sleep 2; do{ warn "Graceful exit!\n"; exit } if $EXIT; }

    Send this a ^C and it will exit gracefully. You can set signal handlers for other signals if desired using syntax like $SIG{INT} = $SIG{HUP} = sub{...} You can't catch a SIGKILL as the OS needs some untrappable way to kill code.

    cheers

    tachyon

Re: shutdown gracefully - kill signal trap
by linux454 (Pilgrim) on Sep 24, 2004 at 14:05 UTC
    You will do yourself a lot of good, by reading all the available documentation on signal handlers BEFORE you start to work with them. They can be dangerous and they can cause unexpected behaviour under the right circumstances. In short, do not do anymore than absolutely necessary in the signal handler (re: only set a previously defined/initialized variable.) The simpler the better. The level of danger varies from platform to platform. While I've never used POSIX signals I've heard they are safer.

    Just my $.02, I could be wrong.

      As you note signals in Perl are dangerous. I use them all the time and they do cause the occasional seg fault. I mostly use them for clean exit handling as in the above case where it is a hell of a lot better than just crunching a process with kill -9. Your worst case is a kill -9 and the best case is a controlled exit.

      cheers

      tachyon

Re: shutdown gracefully - kill signal trap
by Anonymous Monk on Sep 24, 2004 at 11:25 UTC
    It might be a good idea to read the perlipc POD. If I recall correct it has a paragraph about signals.