Monitoring file using inotify

I am using inotify to monitor a local file, for example "/ root / temp", using

inotify_add_watch(fd, "/root/temp", mask). 

When this file is deleted, the program will be blocked by the read(fd, buf, bufSize) function read(fd, buf, bufSize) . Even if I create a new file "/ root / temp", the program is still blocked by the read function. I am wondering if inotify can detect that the monitoring file has been created and the read function can get something from fd so that the read will not be blocked forever. Here is my code:

 uint32_t mask = IN_ALL_EVENTS; int fd = inotify_init(); int wd = inotify_add_watch(fd, "/root/temp", mask); char *buf = new char[1000]; int nbytes = read(fd, buf, 500); 

I tracked all the events.

+4
source share
2 answers

The problem is that read is the default lock.

If you do not want to block it, use select or poll before read . For instance:

 struct pollfd pfd = { fd, POLLIN, 0 }; int ret = poll(&pfd, 1, 50); // timeout of 50ms if (ret < 0) { fprintf(stderr, "poll failed: %s\n", strerror(errno)); } else if (ret == 0) { // Timeout with no events, move on. } else { // Process the new event. struct inotify_event event; int nbytes = read(fd, &event, sizeof(event)); // Do what you need... } 

Note : unverified code.

+16
source

To see the created new file, you need to look at the directory, not the file. File monitoring should appear when it is deleted (IN_DELETE_SELF), but cannot determine if a new file with the same name has been created.

You should probably look at the directory for IN_CREATE | IN_MOVED_TO to see newly created files (or files moved from another location).

Some editors and other tools (such as rsync) can create a file under a different name and then rename it.

+2
source

Source: https://habr.com/ru/post/1335186/


All Articles