I want to use the inotify
mechanism on Linux. I want my application to know when a file aaa
was changed. Can you please provide me with a sample how to do that?
相关问题
- Is shmid returned by shmget() unique across proces
- how to get running process information in java?
- Error building gcc 4.8.3 from source: libstdc++.so
- Why should we check WIFEXITED after wait in order
- Null-terminated string, opening file for reading
why reinvent the wheel? there is already an application called
inotifywait
that watches files usinginotify
from terminal 1
from terminal 2
here is what is seen on terminal 1
Below is a snippet of how you can use inotify to watch "aaa". Note that I haven't tested this, I haven't even compiled it! You will need to add error checking to it.
Instead of using a blocking read you can also use poll/select on inotfd.
The
inotify
C APIinotify
provides three system calls to build file system monitors of all kinds:inotify_init()
creates an instance of theinotify
subsystem in the kernel and returns a file descriptor on success and-1
on failure. Like other system calls, ifinotify_init()
fails, checkerrno
for diagnostics.inotify_add_watch()
, as its name implies, adds a watch. Each watch must provide a pathname and a list of pertinent events, where each event is specified by a constant, such asIN_MODIFY
. To monitor more than one event, simply use the logical or — the pipe (|) operator in C—between each event. Ifinotify_add_watch()
succeeds, the call returns a unique identifier for the registered watch; otherwise, it returns-1
. Use the identifier to alter or remove the associated watch.inotify_rm_watch()
removes a watch.The
read()
andclose()
system calls are also needed. Given the descriptor yielded byinotify_init()
, callread()
to wait for alerts. Assuming a typical file descriptor, the application blocks pending the receipt of events, which are expressed as data in the stream. The common close() on the file descriptor yielded frominotify_init()
deletes and frees all active watches as well as all memory associated with the inotify instance. (The typical reference count caveat applies here, too. All file descriptors associated with an instance must be closed before the memory consumed by the watches and by inotify is freed.)This example adds a watch on the directory /home/rlove/Desktop for any modifications, file creations or file deletions.
Since the initial question seems to mention Qt as a tag as noted in several comments here, search engines may have lead you here.
If somebody want to know how to do it with Qt, see http://doc.qt.io/qt-5/qfilesystemwatcher.html for the Qt-version. On Linux it uses a subset of Inotify, if it is available, see explanation on the Qt page for details.
Basically the needed code looks like this:
in mainwindow.h add :
and for mainwindow.cpp:
also add the slots in mainwindow.cpp which are called if a file/directory-change is noticed: