tags:

views:

48

answers:

3

Hi

im working in a code that detects changes in a file (a log file) then its process the changes with the help of fseek and ftell. but if the file get deleted and changed (with logrotate) the program stops but not dies, because it not detect more changes (even if the file is recreated). fseek dont show errors and eiter ftell. how i can detect that file deletion? maybe a way to reopen the file with other FILE *var and comparing file descriptor. but how i can do that. ?

+1  A: 

You can periodically close the file and open it again, that way you will open the newly created one. Files actually get deleted when there is no handle to the file (open file descriptor is a handle), you are still holding the old file.

Let_Me_Be
i cannot do that, because i constant check the size of the file and keep jumping between the previews last char to the new last char (and process the changes)
Freaktor
+2  A: 

When a file gets deleted, it is not necessarily erased from your disk. In your case the program still has a handle to the old file. The old file handle will not get you any information about its deletion or replacement with another file.

An easy way to detect file deletion and recreation is using stat(2) and fstat(2). They give you a struct stat which contains the inode for the file. When a file is recreated (and still open) the files (old open and recreated) are different and thus the inodes are different. The inode field is st_ino. Yes, you need to poll this unless you wish to use Linux-features like inotify.

Helmut
so, when first open the file, i need to do an stat and in every iteration for changes,check with other stat if the inodes are different , if they are, the file was moved/changed and do something...
Freaktor
A: 

On windows, you could set callbacks on the modifications of the FS. Here are details: http://msdn.microsoft.com/en-us/library/aa365261(VS.85).aspx

ruslik
nice. i forgot to tell, the program run in a posix system.
Freaktor