help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Best way to check file modification time?


From: Barry Margolin
Subject: Re: Best way to check file modification time?
Date: Tue, 17 Nov 2015 11:04:35 -0500
User-agent: MT-NewsWatcher/3.5.3b3 (Intel Mac OS X)

In article <db0g80F14poU1@mid.individual.net>,
 Joost Kremers <joost.m.kremers@gmail.com> wrote:

> Hi all,
> 
> I'm dealing with files that I do not visit directly, instead I read
> their contents into a temp buffer and parse them. At a later point, I
> write the new contents into a temp buffer and save them to the original
> file, overwriting the previous version.
> 
> I would like to check whether the original file may have been
> overwritten by some other process (possibly by Emacs itself if the user
> visits the same file in a buffer, but also by external programs).
> 
> Right now, I'm essentially doing the following:
> 
> ```
> (setq my-file-modtime (nth 5 (file-attributes my-file)))
> (my-parse-function file)
> ```
> 
> where `my-parse-function' reads the contents of FILE into a temp buffer
> and does the parsing. IOW, there is a function call between saving the
> mod time and reading the file.
> 
> Saving is basically the same: the mod time of the file on disk is read
> again and checked against the saved mod time, then if that checks out, a
> function is called that creates the temp buffer, writes out the
> information and saves the file.
> 
> Now, it seems to me that there may be too much time between checking the
> mod time and reading/saving the file, such that it is in principle
> possible that the relevant file gets overwritten at just the wrong moment.
> 
> I can easily move the mod time checking to a position in the code that's
> closer to the actual reading or saving of the file, but I suspect that
> only reduces the problem, it doesn't eliminate it altogether. So I'm
> wondering if there's a Right Way’Ñ¢ to do this. If not, any advice on how
> to reduce the risks as much as possible would be great!

The same window exists when visiting files normally. There's no way to 
get the mod time and read a file atomically.

Instead of saving the file's modification time, remember the time that 
you started reading the file. Then when you're about to save it, see if 
the mod time is newer than that.

This can potentially run into a problem if the file is on a server and 
there's clock skew between the client and server, but that's a common 
problem.

-- 
Barry Margolin, barmar@alum.mit.edu
Arlington, MA
*** PLEASE post questions in newsgroups, not directly to me ***


reply via email to

[Prev in Thread] Current Thread [Next in Thread]