Monitoring file events

1. Role:

  A file or directory to monitor, detect if certain events occur.

2. Related api

int inotify_init();

  Create a monitoring instance, returns a handle.

int inotify_add_watch(int fd, const char *pathname, uint32_t mask);

  Add monitoring events returns monitor descriptor.

  Note: inotify_add_watch have to file a one-time read operation, it is necessary to have read access.

int inotify_rm_watch(int fd, uint32_t wd);

   Delete entry monitoring

3.inotify_event

inotify_event {struct 
    int WD; // monitor descriptor 
    uint32_t mask; // event 
    uint32_t cookie; // related events, only to rename 
    uint32_t len; // name field length 
    char name []; // optional to null end of the string 
}

  

 

   Use read may obtain one or more event.

  If you read a shortage of buf event, it fails, the return EINVAL.

  The minimum length of sizeof read buf (struct inotify_event) + MAX_NAME_LEN + 1

  inotify is a circular queue, it can be described sequence of events.

  If the newly added event each domain the same as the last event, then the kernel will merge, which means that inotify can not describe the incident frequency.

4. Examples

#include <stdio.h>
#include <unistd.h>
#include <sys/inotify.h>
 
#define NAME_MAX	1024
#define BUF_LEN		(10 * (sizeof(struct inotify_event) + NAME_MAX + 1))

void displayInotifyEvent(struct inotify_event *i)
{
	printf("name : %s\n", i->name);
	printf("mask = ");
	if (i->mask & IN_DELETE_SELF)		printf("IN_DELETE_SELF\n");
	if (i->mask & IN_OPEN)			printf("IN_OPEN\n");
	if (i->mask & IN_MODIFY)		printf("IN_MODIFY\n");
}

int main(int argc, char **argv)
{
	int inotifyFd, i, numRead;
	char *p, buf[BUF_LEN];
	struct inotify_event *event;
if (argc < 2) return 0; inotifyFd = inotify_init(); for (i = 1; i < argc; i++) inotify_add_watch(inotifyFd, argv[i], IN_MODIFY | IN_OPEN); inotify_add_watch(inotifyFd, argv[i], IN_DELETE_SELF | IN_MODIFY | IN_OPEN); for (;;) { numRead = read(inotifyFd, buf, BUF_LEN); if (0 == numRead) break; if (0 > numRead) { printf("failed to read\n"); return -1; } for (p = buf; p < buf + numRead;) { event = (struct inotify_event *)p; displayInotifyEvent(event); p += sizeof(struct inotify_event) + event->len; } } return 0; }

  

Guess you like

Origin www.cnblogs.com/yangxinrui/p/11495176.html