Take the 2-minute tour ×

I am writing a program in ANSI C, that takes PID as an argument and needs to print on stdout information about a file name every time, when that given PID opens or closes any file.

Basicly we know, that /proc/PID/fd directory contains symlinks to the files, used by a PID.

By readdir()'ing that directory in a while loop and readlink()'ing each element - I can get file names of all files, currently opened by a PID and print them to stdout. But that doesn't fully solve my original task - I need to print to STDOUT only events of changes in Opened File Descriptor Table for a PID. Moreover, I need to catch not only when new file is opened, but also when it's FD is closed.

So, I need some mechanism to catch file access events for a given PID in a user-space.

I also tried to use inotify() mechanism to catch IN_OPEN / IN_CLOSE, but that only works for regural directories, not for /proc (procfs) ! When I add inotify_watch for /proc/PID/fd directory - it simply doesn't catch any events (most likely due to the nature of PROCFS)

Could you please suggest mechanism to solve my task ? P.S. And sorry for my bad english.

share|improve this question
Is the PID in question going to be run by the same user as the watcher program? Do you need 100% accuracy or would some "missed" events be OK? –  John Zwinck Apr 21 '12 at 14:21
We assume that watcher program is running with root user priveleges. To the question about missed events - it depends on the amount of missed events. In fact, this is programming task in university, so I really don't think that it requires deep kernel-level programming, or writing some daemon-level program, catching kernel FS events. It's supposed to be a basic user space utility, so maybe 100% accuracy is not a mandatory requirement. –  user1348356 Apr 21 '12 at 14:31
add comment

1 Answer

If you need Linux-specific solution, you could use fanotify. Check here for example - http://git.infradead.org/users/eparis/fanotify-example.git. You can subscribe for global notifications and then to filter only those, which are for the pid you're interested in.

share|improve this answer
Thanks for your answer, it can be a solution. But due to the fact that this is a university c programming course task, I am afraid it it supposed to use /PROC/PID/FD or FDINFO in this task. –  user1348356 Apr 21 '12 at 14:37
add comment

Your Answer


