Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Implementing the counterpart of BEGIN

by punkish (Priest)
on Feb 03, 2005 at 15:16 UTC ( [id://427664]=perlquestion: print w/replies, xml ) Need Help??

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

elsewhere I learned that putting a BEGIN block in my script
#!/usr/bin/perl -w BEGIN { $0 =~ /^(.*)\\([^\\]*)\.pl$/; our ($path, $script_name) = ($1, $2); open(STDERR, ">>$path/$script_name.err") or die "invisible error"; warn "$0 started ".localtime().$/; }

prints out to the file ?.err any errors or warnings that the script migh encounter during compile time.

My question is -- is there a way to implement a corresponding FINISH block (as opposed to __END__) which will trap any errors in case the script comes to a dead halt?

Now, I can use the die statement whenever something goes wrong, but that can't really trap things like Control-breaks or control-c etc. How do I trap SIGTERM so that the reason for SIGTERM is written out to ?.err as well?

Update: I should mention -- I need to do this on Windows.

Considered by dragonchild - Retitle to "How do I trap signals on Win32"
Unconsidered by castaway - Keep/Edit/Delete: 8/19/0 - Its fine as is, no putting words in the OPs mouth

Replies are listed 'Best First'.
Re: Implementing the counterpart of BEGIN
by Crian (Curate) on Feb 03, 2005 at 15:20 UTC

    You are looking for perldoc sigtrap I suppose.

      use sigtrap 'handler', \&my_handler, 'normal-signals'; sub my_handler { open(STDERR, ">>test.err") or die "invisible error"; warn "die-ing at " . localtime() . " because of: $!\n"; }

      does the job. Many thanks for your quick help.

Re: Implementing the counterpart of BEGIN
by Anonymous Monk on Feb 03, 2005 at 15:38 UTC
    There's no way you can get the reason for a signal by trapping it. A signal is a 1 bit message, just saying "there's a signal". (Or 6 (or some other number depending on your OS) bits, if you consider the signal number to be part of the message). There's no room for any more information. No reason. Not even who send you the signal.

    You can trap each individual signal (well, except SIGSTOP and SIGKILL) though (use %SIG), so you can log which signal arrived.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://427664]
Approved by grinder
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (9)
As of 2024-04-23 18:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found