Two questions on die{} and writing error to file
am 27.07.2006 00:32:24 von Rob Thomp
Hi there!
I'm writing my first perl code and would like to have my program's result to
a file. I'm handling errors like this:
....
else {
die "file is not valid at line $Num! ";
}
How can I write this error to a (log)file before my program dies? Should I
use this in each case when I have die{} ?
else {
open ($LOG_FILE_HANDLE, ">mylog.log" ) || die "main() : mylog.log" ;
print $LOG_FILE_HANDLE "Error: file is not valid at line $Num!";
close( $LOG_FILE_HANDLE) ;
Or is there a professional solution for this?
Another question is, that if my program is running, and for some reason it
terminates / hangs (because of interruption, resetting computer due to
power-cut, shut down..etc) how can I write to a logfile that a failure
occured and the program was terminated?
I'm using logfile handling as above.
Thanks for the help,
rob
Re: Two questions on die{} and writing error to file
am 27.07.2006 22:31:01 von Joe Smith
Rob Thomp wrote:
> How can I write this error to a (log)file before my program dies? Should I
> use this in each case when I have die{} ?
You want the logic that opens the error log to be in one place, not all over.
Write a sub mydie{}, then replace all occurrences of die() with mydie().
> open ($LOG_FILE_HANDLE, ">mylog.log" ) || die "main() : mylog.log" ;
> print $LOG_FILE_HANDLE "Error: file is not valid at line $Num!";
> close( $LOG_FILE_HANDLE) ;
Note: Append to the log file, don't truncate it. Use lexical file handles.
Use the three-argument form of open().
sub mydie {
open my $log, '>>', $LOGFILENAME or warn "Cannot append to $LOGFILENAME";
print $log @_ or warn "Problem writing to $LOGFILENAME";
die @_;
}
> Another question is, that if my program is running, and for some reason it
> terminates / hangs (because of interruption, resetting computer due to
> power-cut, shut down..etc) how can I write to a logfile that a failure
> occured and the program was terminated?
1. If the process is forceably terminated, there is nothing the process can do.
2. If the computer's RESET button is pressed, there is nothing you can do.
3. If the power is cut off (no UPS), there is nothing you can do.
4. If the process might get stuck in an infinite loop or wait forever for
input that never arrives, then you can use the built-in alarm() function
to do something when time is up.
Or you could fork() a child to do the work and have the parent stick
around to log the status of the child. Using a process "nanny" like this
would let you handle item #1 above, or be an alternative to #4.
-Joe