[英]Linux: How do I find out if a file has been updated by another process?
I am currently watching an XML file from log4j output. 我目前正在观看log4j输出的XML文件。 I have a custom viewer that displays the log-output in GUI.
我有一个自定义查看器,在GUI中显示日志输出。 I need to watch this file as to when it gets updated so that the GUI can re-parse and update itself.
我需要观察这个文件何时更新,以便GUI可以重新解析和更新自己。 In C# there is a FileWatcher concept so on Windows no-probs, but what options do i have using C on Linux.
在C#中有一个FileWatcher概念,所以在Windows上没有probs,但我在Linux上使用C有什么选择。
Is there a standard way of doing this on both unix and linux flavours (POSIX maybe)? 有没有一种标准的方法在unix和linux版本(POSIX可能)上执行此操作?
Thanks 谢谢
John mentioned the two main routes you can take for watching files under Unix/Linux systems: notification and polling. John提到了在Unix / Linux系统下观看文件可以采取的两条主要途径:通知和轮询。
Notification is when the system itself (usually the kernel) triggers a message to registered applications whenever the file is accessed or written to. 通知是指系统本身(通常是内核)在访问或写入文件时向注册的应用程序发出消息的时间。 This approach requires a compliant system and might not be available on older machines.
此方法需要兼容的系统,可能在旧机器上不可用。
The primary implementation of notification under Linux is inotify , which is built into kernels 2.6.13 and later and can be patched into 2.6.12 and earlier. Linux下通知的主要实现是inotify ,它内置于2.6.13及更高版本的内核中,可以修补到2.6.12及更早版本。 There's a nice IBM guide on using inotify as well as a basic set of tools and C library for accessing inotify.
有一个很好的IBM指南,关于使用inotify以及一组基本工具和C库来访问inotify。
Polling is when your program repeatedly checks a file at intervals to see if anything about that file - its size, last modification time, owner, etc. - has been changed. 轮询是指您的程序每隔一段时间反复检查一个文件,以查看该文件的任何内容 - 其大小,上次修改时间,所有者等 - 是否已更改。
There's no standard implementation of this, as it's written on a program-level rather than system-level basis, although the system call poll exists and seems to do something useful for this purpose (the man page says it's similar to select , and it waits for an event to become available on a file descriptor). 这没有标准的实现,因为它是在程序级而不是系统级的基础上编写的,尽管系统调用轮询存在并且似乎为此目的做了一些有用的事情(手册页说它类似于select ,它等待使事件在文件描述符上可用)。 You could also take the more basic approach with stat and do your checking on your own.
你也可以采取与更基本的方法统计 ,做你检查你自己的。
If you want something more portable than inotify, which is a Linux-ism, look into the File Alteration Monitor , which is older and more portable technology, but can be less performant. 如果你想要比inotify更便携的东西,这是一个Linux主义,请查看文件更改监视器 ,它是更老,更便携的技术,但性能较差。 On the other hand, it does something useful with NFS-mounted filesystems, which depending on your application could be important.
另一方面,它对NFS安装的文件系统有用,这取决于你的应用程序可能很重要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.