Linux下inotify的基本使用及注意事项_Shreck66的博客-CSDN博客_inotify.h使用
inotify 机制_inotify_event_hanpfei的博客-CSDN博客
inotify使用范例_cyq1028的博客-CSDN博客_inotify 示例
这三篇文章介绍的很详细了。
下面是我写的一个简单用法:
#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <sys/inotify.h>
using namespace std;
#define BUF_LEN 1024
int displayInotifyEvent(struct inotify_event *e)
{
cout<<"wd="<<e->wd<<endl;
cout<<"cookie = "<<e->cookie<<endl;
cout<<"mask: "<<endl;;
if (e->mask & IN_ACCESS)
cout<<"文件被访问"<<endl;
if (e->mask & IN_ATTRIB)
cout<<"========================================="<<"文件元数据改变"<<endl;
if (e->mask & IN_CLOSE_WRITE)
cout<<"关闭为了写入而打开的文件"<<endl;
if (e->mask & IN_CLOSE_NOWRITE)
cout<<"关闭只读方式打开的文件"<<endl;
if (e->mask & IN_CREATE)
cout<<"在监听目录内创建了文件/目录"<<endl;
if (e->mask & IN_DELETE)
cout<<"在监听目录内删除文件/目录"<<endl;
if (e->mask & IN_DELETE_SELF)
{
cout<<"监听目录/文件本身被删除"<<endl;
return 1;
}
if (e->mask & IN_MODIFY)
cout<<"文件被修改"<<endl;
if (e->mask & IN_MOVE_SELF)
cout<<"受监控目录/文件本身被移动"<<endl;
if (e->mask & IN_MOVE)
cout<<"文件被移"<<endl;
if (e->mask & IN_MOVED_FROM)
{
cout<<"文件被移过来"<<endl;
}
if (e->mask & IN_MOVED_TO)
{
cout<<"文件被移动到Y"<<endl;
}
if (e->mask & IN_OPEN)
cout<<"文件被打开"<<endl;
if (e->len > 0)
{
cout<<"name="<<e->name<<endl;
}
return 0;
}
int main(int argc,char **argv)
{
int inotifyFd, wd, j;
char buf[BUF_LEN];
ssize_t numRead;
char *p;
struct inotify_event *event;
int flags;
inotifyFd = inotify_init();
if (inotifyFd == -1)
{
cout<<"init failed"<<endl;
return 0;
}
wd = inotify_add_watch(inotifyFd, argv[1], IN_ALL_EVENTS);
if (wd == -1)
{
cout<<"error"<<endl;
}
cout<<"watching wd is "<<wd<<endl;
int result=-1;
while(true)
{
if (result == 1)
{
cout<<"again"<<endl;
inotifyFd = inotify_init();
cout<<"inotifyFd is "<<inotifyFd<<endl;
wd = inotify_add_watch(inotifyFd, argv[1], IN_ALL_EVENTS);
cout<<"new wd is "<<wd<<endl;
//auto processResult = std::async(PrintFileContent);
}
numRead = read(inotifyFd, buf, BUF_LEN);
if (numRead == -1)
{
cout<<"read error"<<endl;
}
cout<<"read "<<(long)numRead<<" bytes from inotify fd "<<inotifyFd<<endl;
for (p=buf; p<buf+numRead;)
{
event = (struct inotify_event *)p;
result = displayInotifyEvent(event);
if (result == 1)
break;
p += sizeof(struct inotify_event) + event->len;
}
}
return 0;
}
cmake_minimum_required(VERSION 3.5)
project(logger LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_executable(logger main.cpp)
find_package(Threads REQUIRED)
set(ENABLE_GTEST TRUE)
target_include_directories(logger PUBLIC
${LOG_INCLUDE_PATH}
${LOG_INCLUDE_PATH}/libstream
)
target_link_libraries(${PROJECT_NAME} PRIVATE
pthread
)
在监视文件时,文件变化有时会有连接断开的情况,如果文件没被删除,则重新监听。
下图是我用gedit打开被监听文件时产生的事件。文件处于打开的状态,但是监听到了关闭事件。
然后我修改了文件,并点击保存,产生如下图事件。可以看到文件又被打开和关闭一次,被删除了一次。