Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
This is the sample program to notify us when the file /tmp/myinput is modified
/*This is the sample program to notify us when the file /tmp/myinput is modified */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <linux/inotify.h>
#define EVENT_SIZE ( sizeof (struct inotify_event) )
#define EVENT_BUF_LEN ( 1024 * ( EVENT_SIZE + 16 ) )
int main() {
int length;
int fd;
int wd;
char buffer[EVENT_BUF_LEN];
/*creating the INOTIFY instance*/
fd = inotify_init();
/*checking for error*/
if ( fd < 0 ) {
perror( "inotify_init" );
/*adding the “/tmp” directory into watch list. Here, the suggestion is to validate the existence of the directory before adding into monitoring list.*/
wd = inotify_add_watch( fd, "/tmp/myinput", IN_MODIFY );
int i=0;
/*read to determine the event change happens on “/tmp” directory. Actually this read blocks until the change event occurs*/
length = read( fd, buffer, EVENT_BUF_LEN );
printf("got something\n");
/*checking for error*/
if ( length < 0 ) {
perror( "read" );
/*actually read return the list of change events happens. Here, read the change event one by one and process it accordingly.*/
while ( i < length ) {
struct inotify_event *event = ( struct inotify_event * ) &buffer[ i ];
printf( "File s modified.\n");
i += EVENT_SIZE + event->len;
/*removing the “/tmp” directory from the watch list.*/
inotify_rm_watch( fd, wd );
/*closing the INOTIFY instance*/
close( fd );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.