How to watch for file creation/deletion?

How do I write a C program that will watch a directory for file creation/deletion? Maybe it would receive a signal when someone creates a file?

thanks,
Siegfried

Not by default.

This, unfortunately requires polling, and the simplest way would be to monitor the modification time of the directory the files are supposed to appear in.

Not a good thing to do on an NFS mounted file system, unless you had the polling process on the same machine as the NFS share and then used some form of IPC to notify clients.

At http://os.cqu.edu.au/docs/kernel-doc/Documentation/dnotify.txt I found an example. It seems to work for detecting file creation on fedora but not cygwin.

Is using F_NOTIFY as a parameter for fnctl the most standard way of doing this? Someone else said I should be using dbus but I don't know what that is.

Siegfried

The clue is in the name, "Linux Directory Notification".

Cygwin is not Linux.

I have checked NetBSD 2 and Solaris 7 and neither of them support this.

Why not just readdir? Maintain a list of files you get each time and a new file is one that you get in readdir, but not in your list. Of course, if your directory is going to have thousands of files, it isn't a good idea.

@Porter,
Won't the directory modification time change when a file is deleted as well?

Perhaps a program that checks for dir modified time and checks against a maintained a list of files if the mtime has changed...

Yes so cheapest thing to do is monitor that single date, then if that changes delve deeper to find what actually changed.