tags:

views:

148

answers:

3

I'm wriiting a logger on linux.
the logger open a file on init.
and write to that file descriptor as the program run.
if the log file will be deleted after the file descriptor was created,
no exception/error will be detected .
i have tried:

out.fail()
!out.is_open()

i have google this and find this post .
http://www.daniweb.com/forums/thread23244.html

so i understand now that even if the file was deleted by using rm. it is still exist, it was simply unlinked.
what is the best way to handele this?
1. this is a log application so performance is an issue , i don't want to use stat() on every write
2. i don't care if some of the line in the log files will be missing at the start
3. the user is allowed to delete the log file, to start fresh .the logger should reopen the file.

+3  A: 

Files are 'unlinked' by rm.

A file can have many names. When it has no names left, and nobody has it open, then it is reclaimed by the file system and the space it occupies can be reused.

Linux has an API for 'watching' files called inotify, but this is inviting complexity and race conditions.

So the bigger question is, who else is deleting this file when it is run, and why? Convince them not to!

Will
our system lets the user delete the log files so he can start fresh , this is how our system work and i can't change this :(
jojo
then you need to provide a procedure for the user to send a 'truncate' message to the logger, rather than doing a manual delete on the file-system. You need to change something, the current approach won't work by design.
Will
+1  A: 

You've stated in comments that the reason for this is that the user is allowed to delete the log file, and in this case you want the application to start writing a fresh one in its place.

The traditional UNIX mechanism to handle this is to have your program install a signal handler (often for SIGHUP, since that otherwise makes no sense for a daemon). The signal handler includes code to make the program close and reopen the log file.

The user is then instructed that after they delete the log file, they need to send a SIGHUP to the program.

caf
A: 

The only sensible way to handle this is to try to write to the log. If the write fails (most of the time it won't) then you need to find out why. At that point you can do things like using stat to see if the log is still there - if it is, you have some sort of disk full or permission error, which may be difficult or impossible to recover from, if it isn't, re-open and re-try the write.

anon
@Neil rm doesn't realy delete the file it simple unlink it. The file is still exist and used by the application , the writing will succeed.so checking for error won't help
jojo