'What is the proper way to use inotify?
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?
Solution 1:[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.
const char *filename = "aaa";
int inotfd = inotify_init();
int watch_desc = inotify_add_watch(inotfd, filename, IN_MODIFY);
size_t bufsiz = sizeof(struct inotify_event) + PATH_MAX + 1;
struct inotify_event* event = malloc(bufsiz);
/* wait for an event to occur */
read(inotfd, event, bufsiz);
/* process event struct here */
Solution 2:[2]
If all you need is a commandline application, there is one called inotifywait that watches files using inotify
from terminal 1
# touch cheese
# while inotifywait -e modify cheese; do
> echo someone touched my cheese
> done
from terminal 2
echo lol >> cheese
here is what is seen on terminal 1
Setting up watches.
Watches established.
cheese MODIFY
someone touched my cheese
Setting up watches.
Watches established.
Update: use with caution and see the comments.
Solution 3:[3]
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 :
QFileSystemWatcher * watcher;
private slots:
void directoryChanged(const QString & path);
void fileChanged(const QString & path);
and for mainwindow.cpp:
#include <QFileInfo>
#include <QFileSystemWatcher>
watcher = new QFileSystemWatcher(this);
connect(watcher, SIGNAL(fileChanged(const QString &)), this, SLOT(fileChanged(const QString &)));
connect(watcher, SIGNAL(directoryChanged(const QString &)), this, SLOT(directoryChanged(const QString &)));
watcher->addPath("/tmp/"); // watch directory
watcher->addPath("/tmp/a.file"); // watch file
also add the slots in mainwindow.cpp which are called if a file/directory-change is noticed:
void MainWindow::directoryChanged(const QString & path) {
qDebug() << path;
}
void MainWindow::fileChanged(const QString & path) {
qDebug() << path;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | BЈовић |
| Solution 2 | |
| Solution 3 | user2567875 |
