Skip to content
Permalink
398615020d
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
100 lines (79 sloc) 3.02 KB
/* demo_inotify.c
+
+ Demonstrate the use of the poll API.
+
+ Usage: demo_inotify pathname...
+
+ The program monitors each of the files specified on the command line for all
+ possible file events.
+
+*/
// #include <sys/inotify.h>
#include <poll.h>
#include <limits.h>
#include "tlpi_hdr.h"
static void /* Display information from inotify_event structure */
displayPollEvent(struct pollfd *p)
{
short int evp;
printf(" fd =%2d; ", p->fd);
printf(" events = ");
evp = p->events;
if (evp & POLLIN) printf("POLLIN "); /* There is data to read. */
if (evp & POLLPRI) printf("POLLPRI ");/* There is urgent data to read. */
if (evp & POLLOUT) printf("POLLOUT ");/* Writing now will not block. */
if (evp & POLLRDNORM) printf("POLLRDNORM ");/* Normal data may be read. */
if (evp & POLLRDBAND) printf("POLLRDBAND ");/* Priority data may be read. */
if (evp & POLLWRNORM) printf("POLLWRNORM ");/* Writing now will not block. */
if (evp & POLLWRBAND) printf("POLLWRBAND ");/* Priority data may be written. */
if (evp & POLLERR) printf("POLLERR ");/* Error condition. */
if (evp & POLLHUP) printf("POLLHUP ");/* Hung up. */
if (evp & POLLNVAL) printf("POLLNVAL ");/* Invalid polling request. */
/* These are extensions for Linux. */
/*
# define POLLMSG 0x400
# define POLLREMOVE 0x1000
# define POLLRDHUP 0x2000
*/
printf("\n");
}
#define BUF_LEN (10 * (sizeof(struct pollfd) + NAME_MAX + 1))
#define usageErr(a,b) printf(a,b),exit(1)
#define errExit(a) printf(a),exit(1)
#define fatal errExit
int
main(int argc, char *argv[])
{
int inotifyFd, wd, j;
char buf[BUF_LEN] __attribute__ ((aligned(8)));
ssize_t numRead;
char *p;
struct inotify_event *event;
if (argc < 2 || strcmp(argv[1], "--help") == 0)
usageErr("%s pathname...\n", argv[0]);
inotifyFd = inotify_init(); /* Create inotify instance */
if (inotifyFd == -1)
errExit("inotify_init");
/* For each command-line argument, add a watch for all events */
for (j = 1; j < argc; j++) {
wd = inotify_add_watch(inotifyFd, argv[j], IN_ALL_EVENTS);
if (wd == -1)
errExit("inotify_add_watch");
printf("Watching %s using wd %d\n", argv[j], wd);
}
for (;;) { /* Read events forever */
numRead = read(inotifyFd, buf, BUF_LEN);
if (numRead == 0)
fatal("read() from inotify fd returned 0!");
if (numRead == -1)
errExit("read");
printf("Read %ld bytes from inotify fd\n", (long) numRead);
/* Process all of the events in buffer returned by read() */
for (p = buf; p < buf + numRead; ) {
event = (struct inotify_event *) p;
displayInotifyEvent(event);
p += sizeof(struct inotify_event) + event->len;
}
}
exit(EXIT_SUCCESS);
}