Linux-linux文件钩子 inotify

UI设计界面 UI设计界面 主题:1059 回复:2190

Linux-linux文件钩子 inotify

瑾兮 发布于 2017-05-13 字数 1722 浏览 1039 回复 1

Linux检测文件修改
这份代码不知道有什么问题,只能检测到一次文件修改。然后就等待在select函数中了。

之后,每次read后都重新 add_watch 就好了,但是系统函数如果这么做就太傻了吧...

void inotifyTest()
{
int fd = inotify_init(IN_CLOEXEC);
if (fd == -1)
{
std::cout << "Open Error" << std::endl;
return;
}

int wd = inotify_add_watch(fd, "ttf", IN_MODIFY);
if (wd == -1)
{
std::cerr << "add watch error" << std::endl;
return;
}

char buff[1024];
inotify_event* event = NULL;
while (1)
{
fd_set fds;
FD_ZERO(&fds);
FD_SET(fd, &fds);
cout << "Waiting" << endl;
if (select(fd + 1, &fds, NULL, NULL, NULL) > 0)
{
cout << "Processing" << endl;
int len, index = 0;

// read event;
// read event header;
len = read(fd, &buff, sizeof(buff));
// ASSERT len < 1024
// paser
while (index < len)
{
event = (inotify_event*)(buff + index);
cout << "Wd" << event->wd << endl
<< "Len: " << len << endl
<< "name len" << event->len << endl
<< "sizeof event" << sizeof(inotify_event) << endl;

index += sizeof(inotify_event) + event->len;
std::cout << index << endl;
std::cout << "File changed" << std::endl;
}
}
cout << "well done" << endl;

}
inotify_rm_watch(fd, wd);
close(fd);
}

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

支持 Markdown 语法,需要帮助?

评论(1

偏爱自由 2017-08-29 1 楼

你可以参考这个例子

/*

Copyright (C) 2011 ~ 2012 Deepin, Inc.

2011 ~ 2012 Xu Bin

File Watchdog

Author: Xu Bin <xosdeveloper@gmail.com>

Maintainer: Xu Bin <xosdeveloper@gmail.com>

This program is free software: you can redistribute it and/or modify

it under the terms of the GNU General Public License as published by

the Free Software Foundation, either version 3 of the License, or

any later version.

This program is distributed in the hope that it will be useful,

but WITHOUT ANY WARRANTY; without even the implied warranty of

MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the

GNU General Public License for more details.

You should have received a copy of the GNU General Public License

along with this program. If not, see <http://www.gnu.org/licenses/&gt;

*/

include <stdio.h>

include <unistd.h>

include <sys/select.h>

include <errno.h>

include <sys/inotify.h>

int
main (int argc, char **argv)
{
if (argc != 2)
{
printf ("Usage: %s <file/dir> n", argv[0]);
return -1;
}

unsigned char buf[1024] = { 0 };
struct inotify_event *event = NULL;

int fd = inotify_init ();
int wd = inotify_add_watch (fd, argv[1], IN_ALL_EVENTS);

for (;;)
{
fd_set fds;
FD_ZERO (&fds);
FD_SET (fd, &fds);

  if (select (fd + 1, &amp;fds, NULL, NULL, NULL) &gt; 0)
{
  int len, index = 0;
  while (((len = read (fd, &amp;buf, sizeof (buf))) &lt; 0)
     &amp;&amp; (errno == EINTR));
  while (index &lt; len)
    {
      event = (struct inotify_event *) (buf + index);

        /*
        process your data
        event-&gt;mask)
        event-&gt;name)
    */

      index += sizeof (struct inotify_event) + event-&gt;len;
    }
}
}

inotify_rm_watch (fd, wd);

return 0;
}