Ofstream - determine if a file has been deleted between open and closed

I am writing a logger on Linux.
the logger will open the file in init.
and write to this file descriptor when the program starts.
if the log file is deleted after the file descriptor is created,
exception / error not detected.
I tried:

out.fail() !out.is_open() 

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

so now I understand that even if the file was deleted using rm. it still exists, it just got messy.
What is the best way to convey this?
1. this is a log application, so performance is a problem, I do not want to use stat () for each entry. 2. I don't care if any line in the log files is missing at the beginning
3. The user is allowed to delete the log file to start a new one. The registrar must open the file again.

+4
source share
3 answers

Files " disconnected from rm .

A file can have many names. When he has no names left and no one opens it, he returns to the file system and the space that he occupies can be reused.

Linux has an API for viewing files called inotify , but this causes difficulties and race conditions.

So, the main question is: who else deletes this file when it is running, and why? Do not convince them!

+6
source

You indicated in the comments that the reason for this is that the user is allowed to delete the log file, in which case you want the application to start writing new things in their place.

The traditional UNIX mechanism for this is for your program to install a signal handler (often for SIGHUP , because otherwise it does not make sense to the daemon). The signal handler contains code to close the program and reopen the log file.

Then the user is informed that after deleting the log file they need to send SIGHUP to the program.

+1
source

The only sensible way to handle this is to try and write to the log. If the recording fails (in most cases it will not), you need to find out why. At this point, you can do things like using stat to find out if everything in it contains a log - if so, you have some kind of disk error or permission error that may be difficult or impossible to repair if it not so, re-open and try to record again.

0
source

Source: https://habr.com/ru/post/1300280/


All Articles