How to check if a file is being edited? (Ruby)

569 views Asked by At

I am writing some code to write out an email to a file, let you edit it in your own editor, and when you're done you can tell my code to carry on. I'd like to have it catch the common error where you still have the file open, and therefore might not have saved it.

My first attempt was to try to obtain an exclusive lock on the file (using File.flock) but that never caught it. A bit more googling suggests that this is a hard problem.

The best suggestion appears to be to look for common lock files, eg vi foo will make .foo.swp while joe foo will make .#foo.

So the question is, is there a better way to tell if a file is being edited? And if not, is there a list of all common lock file naming conventions?

2

There are 2 answers

1
rampion On

Use system("#{ENV['EDITOR']} #{path}) to call up their editor of choice. The program will continue when that process ends, ie, they exit their editor.

If you don't trust them to exit their editor, you could fork off a process to watch the file's modification time, and queue off the rest of the program when the modification time changes (though this may happen multiple times if they save incrementally).

1
riri On

lsof gets a list of open files somehow, possibly by searching in /proc/[pid]/, as well as the approaches you suggest for finding checking for swap/temp files.