Plan 9 from Bell Labs’s /usr/web/sources/contrib/maht/limbo/iwatchdir.c

Copyright © 2021 Plan 9 Foundation.
Distributed under the MIT License.
Download the Plan 9 distribution.


#include <stdio.h>
#include <stdlib.h>
#include <string.h> 
#include <inotifytools/inotifytools.h>
#include <inotifytools/inotify.h> 

/*
 * libinotifytools example program.
 * Compile with gcc -linotifytools example.c
 */

char *
escape(char *t) {
	char *p, *e, *escaped;
	int ticks = 0;
	if(t) {
		for(p = t; *p; p++)
			switch(*p) {
			case '\'' :
			case '\\' :
			case '\n' :
			case '\r' :
			case '\t' :
				ticks++;
			}

		e = escaped = malloc(strlen(t) + ticks + 1);
	
		for(p = t; *p; p++) {
			switch(*p) {
			case '\'' :
				*e = *p;
				e++;
				*e = *p;
				break;
			case '\\' :
				*e = '\\';
				e++;
				*e = '\\';
				break;
			case '\n' :
				*e = '\\';
				e++;
				*e = 'n';
				break;
			case '\r' :
				*e = '\\';
				e++;
				*e = 'r';
				break;
			case '\t' :
				*e = '\\';
				e++;
				*e = 't';
				break;
			default :
				*e = *p;
			}
			e++;
		}
	} else {
		e = escaped = malloc(1);
	}
	*e = 0;
	return escaped;
}


int 
main(int argc, char *argv[]) {
        // initialize and watch the entire directory tree from the current working
        // directory downwards for all events

	char *dir = ".";

	if(argc == 2)
		dir = argv[1];

	if (!(inotifytools_initialize() && inotifytools_watch_recursively(dir, IN_ALL_EVENTS))) {
		fprintf(stderr, "%s : %s\n", dir, strerror(inotifytools_error()));
		return -1;
	}

	struct inotify_event * event = inotifytools_next_event(-1);

	char *filename, *eventname;
	while(event) {
		filename = escape(inotifytools_filename_from_wd(event->wd));
		eventname = escape(event->len > 0 ? event->name : 0);
		fprintf(stdout, "'%s'	%d	'%s'\n", filename, event->mask,  eventname);
		fflush(stdout);
		free(filename);
		free(eventname);
		event = inotifytools_next_event(-1);
        }
}

Bell Labs OSI certified Powered by Plan 9

(Return to Plan 9 Home Page)

Copyright © 2021 Plan 9 Foundation. All Rights Reserved.
Comments to [email protected].