如何检查文件是否正在被编辑? (红宝石)
我正在编写一些代码来将电子邮件写入文件,让您在自己的编辑器中编辑它,完成后您可以告诉我的代码继续。我想让它捕获常见错误,即您仍然打开文件,因此可能没有保存它。
我的第一次尝试是尝试获取文件的独占锁(使用 File .flock),但从未捕获它。更多的谷歌搜索表明这是一个难题。
最好的建议似乎是寻找常见的锁定文件,例如 vi foo
将生成 .foo.swp
而 joe foo
将生成 .#foo
.
那么问题来了,有没有更好的方法来判断文件是否正在被编辑呢?如果没有,是否有所有常见锁定文件命名约定的列表?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
system("#{ENV['EDITOR']} #{path})
调用他们选择的编辑器。当该进程结束时,程序将继续,即,他们退出编辑器。如果如果您不信任它们退出编辑器,您可以分叉一个进程来观察文件的修改时间,并在修改时间更改时将程序的其余部分排队(尽管如果它们增量保存,这可能会发生多次)。
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).
lsof 以某种方式获取打开文件的列表,可能是通过在 /proc/[pid]/ 中搜索,以及您建议的查找交换/临时文件检查的方法。
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.