Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ofstream - detect if file has been deleted between open and close

Tags:

c++

file

linux

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.

like image 739
jojo Avatar asked Feb 27 '23 15:02

jojo


1 Answers

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!

like image 137
Will Avatar answered Mar 05 '23 15:03

Will