fanotify(7)
๐ธ fanotify(7) ๐ธ
okay bestie, listen up โ this one lives in the Miscellaneous Information Manual, and it is lowkey one of the most powerful things Linux has going on. I'm obsessed. ๐ซถ
โจ NAME โจ
fanotify โ monitoring filesystem events
๐ฆ DESCRIPTION ๐ฆ
so basically, the fanotify API hands you notification and interception of filesystem events. and like, use cases?? virus scanning, hierarchical storage management โ the whole crown ๐. In the original fanotify API, only a limited set of events was supported. In particular, there was no support for create, delete, and move events. that support got added in Linux 5.1. (if you wanna see the details of an API that did notify those events pre Linux 5.1, go read inotify(7). iykyk.)
Additional capabilities compared to the inotify(7) API include the ability to monitor all of the objects in a mounted filesystem, the ability to make access permission decisions, and the possibility to read or modify files before access by other applications. ate that up fr fr. ๐
The following system calls are used with this API: fanotify_init(2), fanotify_mark(2), read(2), write(2), and close(2).
๐ fanotify_init(), fanotify_mark(), and notification groups
The fanotify_init(2) system call creates and initializes an fanotify notification group and returns a file descriptor referring to it. that fd? your new bestie.
An fanotify notification group is a kernel-internal object that holds a list of files, directories, filesystems, and mounts for which events shall be created.
For each entry in an fanotify notification group, two bit masks exist: the mark mask and the ignore mask. The mark mask defines file activities for which an event shall be created. The ignore mask defines activities for which no event shall be generated. Having these two types of masks permits a filesystem, mount, or directory to be marked for receiving events, while at the same time ignoring events for specific objects under a mount or directory. two masks, one vibe check. ๐
The fanotify_mark(2) system call adds a file, directory, filesystem, or mount to a notification group and specifies which events shall be reported (or ignored), or removes or modifies such an entry.
A possible usage of the ignore mask is for a file cache. Events of interest for a file cache are modification of a file and closing of the same. Hence, the cached directory or mount is to be marked to receive these events. After receiving the first event informing that a file has been modified, the corresponding cache entry will be invalidated. No further modification events for this file are of interest until the file is closed. Hence, the modify event can be added to the ignore mask. Upon receiving the close event, the modify event can be removed from the ignore mask and the file cache entry can be updated. see how the mask does a little dance?? iconic. ๐ง
The entries in the fanotify notification groups refer to files and directories via their inode number and to mounts via their mount ID. If files or directories are renamed or moved within the same mount, the respective entries survive. If files or directories are deleted or moved to another mount, or if filesystems or mounts are unmounted, the corresponding entries are deleted. gone. poof. deleted from the group. ๐
๐ The event queue
As events occur on the filesystem objects monitored by a notification group, the fanotify system generates events that are collected in a queue. These events can then be read (using read(2) or similar) from the fanotify file descriptor returned by fanotify_init(2).
Two types of events are generated: notification events and permission events.
- Notification events are merely informative and require no action to be taken by the receiving application โ with one exception: if a valid file descriptor is provided within a generic event, that file descriptor must be closed. not optional bestie, close it. ๐ช
- Permission events are requests to the receiving application to decide whether permission for a file access shall be granted. For these events, the recipient must write a response which decides whether access is granted or not.
An event is removed from the event queue of the fanotify group when it has been read. Permission events that have been read are kept in an internal list of the fanotify group until either a permission decision has been taken by writing to the fanotify file descriptor or the fanotify file descriptor is closed.
๐ Reading fanotify events
Calling read(2) for the file descriptor returned by fanotify_init(2) blocks (if the flag FAN_NONBLOCK was not specified in the call to fanotify_init(2)) until either a file event occurs or the call is interrupted by a signal (see signal(7)).
After a successful read(2), the read buffer contains one or more of the following structures:
struct fanotify_event_metadata {
__u32 event_len;
__u8 vers;
__u8 reserved;
__u16 metadata_len;
__aligned_u64 mask;
__s32 fd;
__s32 pid;
};
Information records are supplemental pieces of information that may be provided alongside the generic fanotify_event_metadata structure. The flags passed to fanotify_init(2) have influence over the type of information records that may be returned for an event. For example, if a notification group is initialized with FAN_REPORT_FID or FAN_REPORT_DIR_FID, then event listeners should also expect to receive a fanotify_event_info_fid structure alongside the fanotify_event_metadata structure, whereby file handles are used to identify filesystem objects rather than file descriptors. Information records may also be stacked, meaning that using the various FAN_REPORT_* flags in conjunction with one another is supported. In such cases, multiple information records can be returned for an event alongside the generic fanotify_event_metadata structure. For example, if a notification group is initialized with FAN_REPORT_TARGET_FID and FAN_REPORT_PIDFD, then an event listener should expect to receive up to two fanotify_event_info_fid information records and one fanotify_event_info_pidfd information record alongside the generic fanotify_event_metadata structure. ๐
Important: fanotify provides no guarantee around the ordering of information records when a notification group is initialized with a stacked based configuration. so do not come for me about order, it's giving chaos. ๐
Each information record has a nested structure of type fanotify_event_info_header. It is imperative for event listeners to inspect the info_type field of this structure in order to determine the type of information record that had been received for a given event.
In cases where an fanotify group identifies filesystem objects by file handles, event listeners should also expect to receive one or more of the below information record objects alongside the generic fanotify_event_metadata structure within the read buffer:
struct fanotify_event_info_fid {
struct fanotify_event_info_header hdr;
__kernel_fsid_t fsid;
unsigned char handle[];
};
In cases where an fanotify group is initialized with FAN_REPORT_PIDFD, event listeners should expect to receive the below information record object alongside the generic fanotify_event_metadata structure within the read buffer:
struct fanotify_event_info_pidfd {
struct fanotify_event_info_header hdr;
__s32 pidfd;
};
In cases where an fanotify group is initialized with FAN_REPORT_MNT, event listeners should expect to receive the below information record object alongside the generic fanotify_event_metadata structure within the read buffer. This structure is defined as follows:
struct fanotify_event_info_mnt {
struct fanotify_event_info_header hdr;
__u64 mnt_id;
};
In case of a FAN_FS_ERROR event, an additional information record describing the error that occurred is returned alongside the generic fanotify_event_metadata structure within the read buffer. This structure is defined as follows:
struct fanotify_event_info_error {
struct fanotify_event_info_header hdr;
__s32 error;
__u32 error_count;
};
In case of FAN_PRE_ACCESS events, an additional information record describing the access range is returned alongside the generic fanotify_event_metadata structure within the read buffer. This structure is defined as follows:
struct fanotify_event_info_range {
struct fanotify_event_info_header hdr;
__u32 pad;
__u64 offset;
__u64 count;
};
All information records contain a nested structure of type fanotify_event_info_header. This structure holds meta-information about the information record that may have been returned alongside the generic fanotify_event_metadata structure. This structure is defined as follows:
struct fanotify_event_info_header {
__u8 info_type;
__u8 pad;
__u16 len;
};
For performance reasons, it is recommended to use a large buffer size (for example, 4096 bytes), so that multiple events can be retrieved by a single read(2). batch your reads bestie, it's the move. โจ
The return value of read(2) is the number of bytes placed in the buffer, or -1 in case of an error (but see BUGS).
The fields of the fanotify_event_metadata structure are as follows:
โญ event_len
This is the size of the data for the current event and the offset to the next event in the buffer. Unless the group identifies filesystem objects by file handles, the value of event_len is always FAN_EVENT_METADATA_LEN. For a group that identifies filesystem objects by file handles, event_len also includes the variable size file identifier records.
๐ vers
This field holds a version number for the structure. It must be compared to FANOTIFY_METADATA_VERSION to verify that the structures returned at run time match the structures defined at compile time. In case of a mismatch, the application should abandon trying to use the fanotify file descriptor. like, just walk away. ๐ถโโ๏ธ
๐ซ reserved
This field is not used. it's giving furniture that comes with the apartment. nothing to do here. ๐ช
๐ metadata_len
This is the size of the structure. The field was introduced to facilitate the implementation of optional headers per event type. No such optional headers exist in the current implementation.
๐ฅ mask
This is a bit mask describing the event (see below).
๐ fd
This is an open file descriptor for the object being accessed, or FAN_NOFD if a queue overflow occurred. With an fanotify group that identifies filesystem objects by file handles, applications should expect this value to be set to FAN_NOFD for each event that is received. The file descriptor can be used to access the contents of the monitored file or directory. The reading application is responsible for closing this file descriptor.
okay so back to that fd you just got handed ๐ โ when you called fanotify_init(2), you may have passed event_f_flags, and all those file status flags you listed get set on the open file description that this file descriptor points to. And then, on top of that, the (kernel-internal) FMODE_NONOTIFY file status flag also gets set on that open file description. What's it for? It suppresses fanotify event generation โจ. So when the receiver of the fanotify event goes and touches the notified file or directory through this file descriptor, no additional events get created. The vibe is: no feedback loops here. ๐
And if your fanotify group was initialized with FAN_REPORT_FD_ERROR, this field will hold a negative error value whenever a file descriptor couldn't be opened โ and in the case of a queue overflow, the value is -EBADF. ๐
pidโ ifFAN_REPORT_TIDwas set infanotify_init(2), this is the TID of the thread that caused the event. Otherwise, it's the PID of the process that caused the event.
A program listening to fanotify events can totally compare this PID against the PID returned by getpid(2) to figure out whether the event was caused by the listener itself, or whether it's from some other process touching a file. Detective moment. ๐ต๏ธโโ๏ธ
the mask bits, i.e. the main character of the whole page ๐
The bit mask in mask tells you which events have actually occurred for a single filesystem object. Multiple bits can be set in this mask if more than one event happened for the monitored filesystem object. And here's the kicker: consecutive events for the same filesystem object coming from the same process may be merged into a single event โ with the one exception that two permission events are never merged into one queue entry. Periodt.
The bits that may appear in mask are as follows:
FAN_ACCESSโ a file or a directory (but see BUGS) was accessed (read). ๐FAN_OPENโ a file or a directory was opened.FAN_OPEN_EXECโ a file was opened with the intent to be executed. See NOTES infanotify_mark(2)for additional details.FAN_ATTRIBโ a file or directory metadata was changed. โจ glow-up โจFAN_CREATEโ a child file or directory was created in a watched parent.FAN_DELETEโ a child file or directory was deleted in a watched parent. ๐FAN_DELETE_SELFโ a watched file or directory was deleted.FAN_RENAMEโ a file or directory has been moved to or from a watched parent directory.FAN_MOVED_FROMโ a file or directory has been moved from a watched parent directory.FAN_MOVED_TOโ a file or directory has been moved to a watched parent directory.FAN_MOVE_SELFโ a watched file or directory was moved.FAN_MODIFYโ a file was modified.FAN_CLOSE_WRITEโ a file that was opened for writing (O_WRONLYorO_RDWR) was closed.FAN_CLOSE_NOWRITEโ a file or directory that was opened read-only (O_RDONLY) was closed.FAN_MNT_ATTACHโ a mount was attached to mount namespace.FAN_MNT_DETACHโ a mount was detached from mount namespace.FAN_FS_ERRORโ a filesystem error was detected. ๐ญFAN_Q_OVERFLOWโ the event queue exceeded the limit on number of events. This limit can be overridden by specifying theFAN_UNLIMITED_QUEUEflag when callingfanotify_init(2).FAN_ACCESS_PERMโ an application wants to read a file or directory, for example usingread(2)orreaddir(2). The reader must write a response (as described below) that determines whether the permission to access the filesystem object shall be granted. So like, you are the gatekeeper bestie ๐ซถFAN_OPEN_PERMโ an application wants to open a file or directory. The reader must write a response that determines whether the permission to open the filesystem object shall be granted.FAN_OPEN_EXEC_PERMโ an application wants to open a file for execution. The reader must write a response that determines whether the permission to open the filesystem object for execution shall be granted. See NOTES infanotify_mark(2)for additional details.
If all you wanna do is check for any close event, this bit mask is the move:
FAN_CLOSEโ a file was closed. This is a synonym for:
FAN_CLOSE_WRITE | FAN_CLOSE_NOWRITE
And for any move event:
FAN_MOVEโ a file or directory was moved. This is a synonym for:
FAN_MOVED_FROM | FAN_MOVED_TO
Heads up: the following bit may appear in mask only in conjunction with other event type bits. It doesn't fly solo.
FAN_ONDIRโ the events described in themaskhave occurred on a directory object. Reporting events on directories requires setting this flag in the mark mask. Seefanotify_mark(2)for additional details. Lowkey important: theFAN_ONDIRflag is reported in an event mask only if the fanotify group identifies filesystem objects by file handles.
the info records ๐
Information records that get supplied alongside the generic fanotify_event_metadata structure will always contain a nested structure of type fanotify_event_info_header. Here are its fields:
info_typeโ a unique integer value representing the type of information record object received for an event. This field can be set to one of the following:FAN_EVENT_INFO_TYPE_FIDFAN_EVENT_INFO_TYPE_DFIDFAN_EVENT_INFO_TYPE_DFID_NAMEFAN_EVENT_INFO_TYPE_PIDFDFAN_EVENT_INFO_TYPE_ERRORFAN_EVENT_INFO_TYPE_RANGEFAN_EVENT_INFO_TYPE_MNT
The value set for this field depends on the flags that were supplied to fanotify_init(2). Peep the field details of each information record object type below to understand all the different cases where the info_type values can be set. iykyk ๐
padโ this field is currently not used by any information record object type, so it's set to zero. Just vibing there, empty. ๐ซฅlenโ the value oflenis set to the size of the information record object, including thefanotify_event_info_header. And bestie, the total size of all additional information records is not expected to be larger than(event_len - metadata_len).
fanotify_event_info_fid ๐ธ
hdrโ this is a structure of typefanotify_event_info_header. For example, when a fanotify file descriptor is created usingFAN_REPORT_FID, a single information record is expected to be attached to the event with aninfo_typefield value ofFAN_EVENT_INFO_TYPE_FID. When a fanotify file descriptor is created using the combination ofFAN_REPORT_FIDandFAN_REPORT_DIR_FID, there may be two information records attached to the event: one withinfo_typefield value ofFAN_EVENT_INFO_TYPE_DFID, identifying a parent directory object, and one withinfo_typefield value ofFAN_EVENT_INFO_TYPE_FID, identifying a child object. And ngl, note this: for the directory entry modification eventsFAN_CREATE,FAN_DELETE,FAN_MOVE, andFAN_RENAME, an information record identifying the created/deleted/moved child object is reported only if the fanotify group was initialized with the flagFAN_REPORT_TARGET_FID. No flag, no child object info. That's the rule, no cap.fsidโ this is a unique identifier of the filesystem containing the object associated with the event. It's a structure of type__kernel_fsid_tand it contains the same value asf_fsidwhen callingstatfs(2). โ ๏ธ Note that some filesystems (e.g.,fuse(4)) report zerofsid. In these cases it's not possible to usefsidto associate the event with a specific filesystem instance, so monitoring different filesystem instances that report zerofsidwith the same fanotify group is not supported. Not me warning you twice. Don't do it. ๐handleโ this field contains a variable-size structure of typestruct file_handle. It's an opaque handle that corresponds to a specified object on a filesystem, as returned byname_to_handle_at(2). You can use it to uniquely identify a file on a filesystem, and you can pass it as an argument toopen_by_handle_at(2). ๐ฏ If the value of theinfo_typefield isFAN_EVENT_INFO_TYPE_DFID_NAME, the file handle is followed by a null terminated string that identifies the created/deleted/moved directory entry name. For other events such asFAN_OPEN,FAN_ATTRIB,FAN_DELETE_SELF, andFAN_MOVE_SELF: if the value of theinfo_typefield isFAN_EVENT_INFO_TYPE_FID, the handle identifies the object correlated to the event. If the value of theinfo_typefield isFAN_EVENT_INFO_TYPE_DFID, the handle identifies the directory object correlated to the event, or the parent directory of a non-directory object correlated to the event. And if the value of theinfo_typefield isFAN_EVENT_INFO_TYPE_DFID_NAME, the handle identifies the same directory object that would be reported withFAN_EVENT_INFO_TYPE_DFIDโ and the file handle is followed by a null terminated string that identifies the name of a directory entry in that directory, or.to identify the directory object itself.
fanotify_event_info_pidfd ๐ฆ
hdrโ this is a structure of typefanotify_event_info_header. When a fanotify group is initialized usingFAN_REPORT_PIDFD, theinfo_typefield value of thefanotify_event_info_headeris set toFAN_EVENT_INFO_TYPE_PIDFD.pidfdโ this is a process file descriptor that refers to the process responsible for generating the event. The returned process file descriptor is literally no different from one you could get manually ifpidfd_open(2)were called onfanotify_event_metadata.pid. Now, in the instance that an error is encountered during pidfd creation, one of two possible error types โ each represented by a negative integer value โ may be returned in thispidfdfield:- In cases where the process responsible for generating the event has terminated prior to the event listener being able to read events from the notification queue,
FAN_NOPIDFDis returned. - The pidfd creation for an event is only performed at the time the events are read from the notification queue. All other possible pidfd creation failures are represented by
FAN_EPIDFD.
- In cases where the process responsible for generating the event has terminated prior to the event listener being able to read events from the notification queue,
And once the event listener has dealt with an event and the pidfd is no longer required, the pidfd should be closed via close(2). Clean up after yourself bestie, that's just good manners. ๐ง
If an fanotify group got set up with FAN_REPORT_FD_ERROR, this field is holding a negative error value when a pidfd creation fails, and if the process has been terminated, the value will literally be -ESRCH. ๐ญ
The fields of the fanotify_event_info_mnt structure are as follows:
.hdrโ this is a structure of typefanotify_event_info_header. The.info_typefield is set toFAN_EVENT_INFO_TYPE_MNT..mnt_idโ identifies the mount associated with the event. It's a 64-bit unique mount id, same one you'd get back fromstatx(2)with theSTATX_MNT_ID_UNIQUEflag. slay ๐ซถ
The fields of the fanotify_event_info_error structure are as follows:
hdrโ this is a structure of typefanotify_event_info_header. Theinfo_typefield is set toFAN_EVENT_INFO_TYPE_ERROR.errorโ identifies the type of error that occurred.error_countโ this is a counter of the number of errors suppressed since the last error was read.
The fields of the fanotify_event_info_range structure are as follows:
hdrโ this is a structure of typefanotify_event_info_header. Theinfo_typefield is set toFAN_EVENT_INFO_TYPE_RANGE.countโ the number of bytes being read or written to the file.offsetโ the offset from which bytes are read or written to the file.
The following macros are provided to iterate over a buffer containing fanotify event metadata returned by a read(2) from an fanotify file descriptor:
FAN_EVENT_OK(meta, size)โ this macro checks the remaining size size of the buffer meta against the size of the metadata structure and theevent_lenfield of the first metadata structure in the buffer.FAN_EVENT_NEXT(meta, size)โ this macro uses the size indicated in theevent_lenfield of the metadata structure pointed to by meta to calculate the address of the next metadata structure that follows meta. size is the number of bytes of metadata that currently remain in the buffer. The macro returns a pointer to the next metadata structure that follows meta, and reduces size by the number of bytes in the metadata structure that has been skipped over (i.e., it subtractsmeta->event_lenfrom size). ๐
In addition, there is:
FAN_EVENT_METADATA_LENโ this macro returns the size (in bytes) of the structurefanotify_event_metadata. This is the minimum size (and currently the only size) of any event metadata.
โจ Monitoring an fanotify file descriptor for events โจ
When an fanotify event occurs, the fanotify file descriptor indicates as readable when you pass it to epoll(7), poll(2), or select(2). ๐
๐ Dealing with permission events ๐
For permission events, the application must write(2) a structure of the following form to the fanotify file descriptor:
struct fanotify_response {
__s32 fd;
__u32 response;
};
The fields of this structure are as follows:
fdโ this is the file descriptor from the structurefanotify_event_metadata.responseโ this field indicates whether or not the permission is to be granted. Its value must contain either the flagFAN_ALLOWto allow the file operation orFAN_DENYto deny the file operation.
If access is denied, the requesting application call will receive an EPERM error. Since Linux 6.13, if a notification group is initialized with class FAN_CLASS_PRE_CONTENT, the file operation can be denied with errors other than EPERM. For example, for the requesting application to get the EIO error, the event listener can write the response FAN_DENY_ERRNO(EIO). At the time of writing, only the following error values could be returned to the application with the FAN_DENY_ERRNO(e) macro: EPERM, EIO, EBUSY, ETXTBSY, EAGAIN, ENOSPC, EDQUOT. ๐ซก
Also bestie, if the notification group has been created with the FAN_ENABLE_AUDIT flag, then the FAN_AUDIT flag can be set in the response field. In that case, the audit subsystem will log information about the access decision to the audit logs. โจ
Since Linux 6.3, the FAN_INFO flag can be set in the .response field. It indicates that an extra variable-length response record follows the fanotify_response structure. Extra response records start with a common header:
struct fanotify_response_info_header {
__u8 type;
__u8 pad;
__u16 len;
};
The value of .type determines the format of the extra response record. ๐
FAN_RESPONSE_INFO_AUDIT_RULEโ the following response record is expected with extra details for the audit log:
struct fanotify_response_info_audit_rule {
struct fanotify_response_info_header hdr;
__u32 rule_number;
__u32 subj_trust;
__u32 obj_trust;
};
๐ Monitoring filesystems for errors ๐
A single FAN_FS_ERROR event is stored per filesystem at once. Extra error messages are suppressed and accounted for in the error_count field of the existing FAN_FS_ERROR event record, but details about the errors are lost. ๐ญ
Errors reported by FAN_FS_ERROR are generic errno values, but not all kinds of error types are reported by all filesystems.
Errors not directly related to a file (i.e., super block corruption) are reported with an invalid handle. For these errors, the handle will have the field handle_type set to FILEID_INVALID, and the handle buffer size set to 0.
๐ช Closing the fanotify file descriptor ๐ช
When all file descriptors referring to the fanotify notification group are closed, the fanotify group is released and its resources are freed for reuse by the kernel. Upon close(2), outstanding permission events will be set to allowed. periodt.
๐ /proc interfaces ๐
The file /proc/pid/fdinfo/fd contains information about fanotify marks for file descriptor fd of process pid. See proc(5) for details. ๐ง
Since Linux 5.13 (and 5.10.220), the following interfaces can be used to control the amount of kernel resources consumed by fanotify:
/proc/sys/fs/fanotify/max_queued_eventsโ the value in this file is used when an application callsfanotify_init(2)to set an upper limit on the number of events that can be queued to the corresponding fanotify group. Events in excess of this limit are dropped, but anFAN_Q_OVERFLOWevent is always generated. Prior to Linux kernel 5.13, the hardcoded limit was16384events./proc/sys/fs/fanotify/max_user_groupโ this specifies an upper limit on the number of fanotify groups that can be created per real user ID. Prior to Linux kernel 5.13, the hardcoded limit was128groups per user./proc/sys/fs/fanotify/max_user_marksโ this specifies an upper limit on the number of fanotify marks that can be created per real user ID. Prior to Linux kernel 5.13, the hardcoded limit was8192marks per group (not per user). ๐
๐จ ERRORS ๐จ
In addition to the usual errors for read(2), the following errors can occur when reading from the fanotify file descriptor:
EINVALโ the buffer is too small to hold the event.EMFILEโ the per-process limit on the number of open files has been reached. See the description ofRLIMIT_NOFILEingetrlimit(2).ENFILEโ the system-wide limit on the total number of open files has been reached. See/proc/sys/fs/file-maxinproc(5).ETXTBSYโ this error is returned byread(2)ifO_RDWRorO_WRONLYwas specified in theevent_f_flagsargument when callingfanotify_init(2)and an event occurred for a monitored file that is currently being executed.
In addition to the usual errors for write(2), the following errors can occur when writing to the fanotify file descriptor:
EINVALโ fanotify access permissions are not enabled in the kernel configuration or the value ofresponsein the response structure is not valid.ENOENTโ the file descriptorfdin the response structure is not valid. This may occur when a response for the permission event has already been written.
๐ STANDARDS ๐
Linux.
๐ฐ๏ธ HISTORY ๐ฐ๏ธ
The fanotify API was introduced in Linux 2.6.36 and enabled in Linux 2.6.37. fdinfo support was added in Linux 3.8. iconic.
๐ NOTES ๐
The fanotify API is available only if the kernel was built with the CONFIG_FANOTIFY configuration option enabled. In addition, fanotify permission handling is available only if the CONFIG_FANOTIFY_ACCESS_PERMISSIONS configuration option is enabled. no cap. ๐
โ ๏ธ Limitations and caveats โ ๏ธ
Fanotify reports only events that a user-space program triggers through the filesystem API. As a result, it does not catch remote events that occur on network filesystems.
The fanotify API does not report file accesses and modifications that may occur because of mmap(2), msync(2), and munmap(2).
Events for directories are created only if the directory itself is opened, read, and closed. Adding, removing, or changing children of a marked directory does not create events for the monitored directory itself.
Fanotify monitoring of directories is not recursive: to monitor subdirectories under a directory, additional marks must be created. The FAN_CREATE event can be used for detecting when a subdirectory has been created under a marked directory. An additional mark must then be set on the newly created subdirectory. This approach is racy, because it can lose events that occurred inside the newly created subdirectory, before a mark is added on that subdirectory. Monitoring mounts offers the capability to monitor a whole directory tree in a race-free manner. Monitoring filesystems offers the capability to monitor changes made from any mount of a filesystem instance in a race-free manner.
The event queue can overflow. In this case, events are lost. ๐ญ๐
๐ BUGS ๐
Okay so listen, before Linux 3.19, fallocate(2) was lowkey not generating fanotify events at all. Silence. Nothing. ๐ But since Linux 3.19? Calls to fallocate(2) DO generate FAN_MODIFY events. We love growth. ๐ฑ
As of Linux 3.17, the following bugs exist โ and no, bestie, they did not get fixed by manifesting:
- ๐ซ One object, so many paths. On Linux, a filesystem object may be accessible through multiple paths. Example: part of a filesystem may get remounted using the
--bindoption ofmount(8). A listener that marked a mount will be notified only of events that were triggered for a filesystem object using the same mount. Any other event will pass unnoticed. Just gone. Not even a "hey girl". ๐ญ - ๐จ No authorization check before the fd gets handed over. When an event is generated, no check is made to see whether the user ID of the receiving process has authorization to read or write the file before passing a file descriptor for that file. That's a whole security risk, specifically when the
CAP_SYS_ADMINcapability is set for programs executed by unprivileged users. Not me being dramatic, this is genuinely a big deal. โ ๏ธ - ๐ The
read(2)error that ghosted you. If a call toread(2)processes multiple events from the fanotify queue and an error occurs, the return value will be the total size of the events successfully copied to the user-space buffer before the error occurred. It will not be-1, anderrnowill not be set. So the reading application literally has no way to detect the error. It's giving silent treatment and it's toxic. ๐
โจ EXAMPLES โจ
Okay so for the fun part: the two example programs below demonstrate the usage of the fanotify API. Grab a snack, we're going in. ๐
๐ธ Example program: fanotify_example.c
The first program is an example of fanotify being used with its event object information passed in the form of a file descriptor. The program marks the mount passed as a command-line argument and waits for events of type FAN_OPEN_PERM and FAN_CLOSE_WRITE. When a permission event occurs, a FAN_ALLOW response is given. That's it, that's the vibe. ๐
The following shell session shows an example of running this program. This session involved editing the file /home/user/temp/notes. Before the file was opened, a FAN_OPEN_PERM event occurred. After the file was closed, a FAN_CLOSE_WRITE event occurred. Execution of the program ends when the user presses the Enter key. ๐
# ./fanotify_example /home;
Press enter key to terminate.
Listening for events.
FAN_OPEN_PERM: File /home/user/temp/notes
FAN_CLOSE_WRITE: File /home/user/temp/notes
Listening for events stopped.
๐ Program source: fanotify_example.c
#define _GNU_SOURCE /* Needed to get O_LARGEFILE definition */
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/fanotify.h>
#include <unistd.h>
/* Read all available fanotify events from the file descriptor 'fd'. */
static void
handle_events(int fd)
{
const struct fanotify_event_metadata *metadata;
struct fanotify_event_metadata buf[200];
ssize_t size;
char path[PATH_MAX];
ssize_t path_len;
char procfd_path[PATH_MAX];
struct fanotify_response response;
/* Loop while events can be read from fanotify file descriptor. */
for (;;) {
/* Read some events. */
size = read(fd, buf, sizeof(buf));
if (size == -1 && errno != EAGAIN) {
perror("read");
exit(EXIT_FAILURE);
}
/* Check if end of available data reached. */
if (size <= 0)
break;
/* Point to the first event in the buffer. */
metadata = buf;
/* Loop over all events in the buffer. */
while (FAN_EVENT_OK(metadata, size)) {
/* Check that run-time and compile-time structures match. */
if (metadata->vers != FANOTIFY_METADATA_VERSION) {
fprintf(stderr,
"Mismatch of fanotify metadata version.\n");
exit(EXIT_FAILURE);
}
/* metadata->fd contains either FAN_NOFD, indicating a
queue overflow, or a file descriptor (a nonnegative
integer). Here, we simply ignore queue overflow. */
if (metadata->fd >= 0) {
/* Handle open permission event. */
if (metadata->mask & FAN_OPEN_PERM) {
printf("FAN_OPEN_PERM: ");
/* Allow file to be opened. */
response.fd = metadata->fd;
response.response = FAN_ALLOW;
write(fd, &response, sizeof(response));
}
/* Handle closing of writable file event. */
if (metadata->mask & FAN_CLOSE_WRITE)
printf("FAN_CLOSE_WRITE: ");
/* Retrieve and print pathname of the accessed file. */
snprintf(procfd_path, sizeof(procfd_path),
"/proc/self/fd/%d", metadata->fd);
path_len = readlink(procfd_path, path,
sizeof(path) - 1);
if (path_len == -1) {
perror("readlink");
exit(EXIT_FAILURE);
}
path[path_len] = '\0';
printf("File %s\n", path);
/* Close the file descriptor of the event. */
close(metadata->fd);
}
/* Advance to next event. */
metadata = FAN_EVENT_NEXT(metadata, size);
}
}
}
int
main(int argc, char *argv[])
{
char buf;
int fd, poll_num;
nfds_t nfds;
struct pollfd fds[2];
/* Check mount point is supplied. */
if (argc != 2) {
fprintf(stderr, "Usage: %s MOUNT\n", argv[0]);
exit(EXIT_FAILURE);
}
printf("Press enter key to terminate.\n");
/* Create the file descriptor for accessing the fanotify API. */
fd = fanotify_init(FAN_CLOEXEC | FAN_CLASS_CONTENT | FAN_NONBLOCK,
O_RDONLY | O_LARGEFILE);
if (fd == -1) {
perror("fanotify_init");
exit(EXIT_FAILURE);
}
/* Mark the mount for:
- permission events before opening files
- notification events after closing a write-enabled
file descriptor. */
if (fanotify_mark(fd, FAN_MARK_ADD | FAN_MARK_MOUNT,
FAN_OPEN_PERM | FAN_CLOSE_WRITE, AT_FDCWD,
argv[1]) == -1) {
perror("fanotify_mark");
exit(EXIT_FAILURE);
}
/* Prepare for polling. */
nfds = 2;
fds[0].fd = STDIN_FILENO; /* Console input */
fds[0].events = POLLIN;
fds[1].fd = fd; /* Fanotify input */
fds[1].events = POLLIN;
/* This is the loop to wait for incoming events. */
printf("Listening for events.\n");
for (;;) {
poll_num = poll(fds, nfds, -1);
if (poll_num == -1) {
if (errno == EINTR) /* Interrupted by a signal */
continue; /* Restart poll() */
perror("poll"); /* Unexpected error */
exit(EXIT_FAILURE);
}
if (poll_num > 0) {
if (fds[0].revents & POLLIN) {
/* Console input is available: empty stdin and quit. */
while (read(STDIN_FILENO, &buf, 1) > 0 && buf != '\n')
continue;
break;
}
if (fds[1].revents & POLLIN) {
/* Fanotify events are available. */
handle_events(fd);
}
}
}
printf("Listening for events stopped.\n");
exit(EXIT_SUCCESS);
}
๐ฆ Example program: fanotify_fid.c
The second program is an example of fanotify being used with a group that identifies objects by file handles. The program marks the filesystem object that is passed as a command-line argument and waits until an event of type FAN_CREATE has occurred. The event mask tells you which type of filesystem object โ either a file or a directory โ was created. Once all events have been read from the buffer and processed accordingly, the program simply terminates. No lingering, no clout chasing. โจ
The following shell sessions show two different invocations of this program, with different actions performed on a watched object. Two flavors, both iconic. ๐
The first session shows a mark being placed on /home/user. This is followed by the creation of a regular file, /home/user/testfile.txt. This results in a FAN_CREATE event being generated and reported against the file's parent watched directory object and with the created file name. Program execution ends once all events captured within the buffer have been processed.
# ./fanotify_fid /home/user;
Listening for events.
FAN_CREATE (file created):
Directory /home/user has been modified.
Entry 'testfile.txt' is not a subdirectory.
All events processed successfully. Program exiting.
$ touch /home/user/testfile.txt; # In another terminal
The second session shows a mark being placed on /home/user. This is followed by the creation of a directory, /home/user/testdir. This specific action results in a FAN_CREATE event being generated and is reported with the FAN_ONDIR flag set, plus the created directory name. ๐
# ./fanotify_fid /home/user;
Listening for events.
FAN_CREATE | FAN_ONDIR (subdirectory created):
Directory /home/user has been modified.
Entry 'testdir' is a subdirectory.
All events processed successfully. Program exiting.
$ mkdir -p /home/user/testdir; # In another terminal
๐ Program source: fanotify_fid.c
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/fanotify.h>
#include <unistd.h>
#define BUF_SIZE 256
int
main(int argc, char *argv[])
{
int fd, ret, event_fd, mount_fd;
ssize_t size, path_len;
char path[PATH_MAX];
char procfd_path[PATH_MAX];
char events_buf[BUF_SIZE];
struct file_handle *file_handle;
struct fanotify_event_metadata *metadata;
struct fanotify_event_info_fid *fid;
const char *file_name;
struct stat sb;
if (argc != 2) {
fprintf(stderr, "Invalid number of command line arguments.\n");
exit(EXIT_FAILURE);
}
mount_fd = open(argv[1], O_DIRECTORY | O_RDONLY);
if (mount_fd == -1) {
perror(argv[1]);
exit(EXIT_FAILURE);
}
/* Create an fanotify file descriptor with FAN_REPORT_DFID_NAME as
a flag so that program can receive fid events with directory
entry name. */
fd = fanotify_init(FAN_CLASS_NOTIF | FAN_REPORT_DFID_NAME, 0);
if (fd == -1) {
perror("fanotify_init");
exit(EXIT_FAILURE);
}
/* Place a mark on the filesystem object supplied in argv[1]. */
ret = fanotify_mark(fd, FAN_MARK_ADD | FAN_MARK_ONLYDIR,
FAN_CREATE | FAN_ONDIR,
AT_FDCWD, argv[1]);
if (ret == -1) {
perror("fanotify_mark");
exit(EXIT_FAILURE);
}
printf("Listening for events.\n");
/* Read events from the event queue into a buffer. */
size = read(fd, events_buf, sizeof(events_buf));
if (size == -1 && errno != EAGAIN) {
perror("read");
exit(EXIT_FAILURE);
}
/* Process all events within the buffer. */
for (metadata = (struct fanotify_event_metadata *) events_buf;
FAN_EVENT_OK(metadata, size);
metadata = FAN_EVENT_NEXT(metadata, size)) {
fid = (struct fanotify_event_info_fid *) (metadata + 1);
file_handle = (struct file_handle *) fid->handle;
/* Ensure that the event info is of the correct type. */
if (fid->hdr.info_type == FAN_EVENT_INFO_TYPE_FID ||
fid->hdr.info_type == FAN_EVENT_INFO_TYPE_DFID) {
file_name = NULL;
} else if (fid->hdr.info_type == FAN_EVENT_INFO_TYPE_DFID_NAME) {
file_name = file_handle->f_handle +
file_handle->handle_bytes;
} else {
fprintf(stderr, "Received unexpected event info type.\n");
exit(EXIT_FAILURE);
}
if (metadata->mask == FAN_CREATE)
printf("FAN_CREATE (file created):\n");
if (metadata->mask == (FAN_CREATE | FAN_ONDIR))
printf("FAN_CREATE | FAN_ONDIR (subdirectory created):\n");
/* metadata->fd is set to FAN_NOFD when the group identifies
objects by file handles. To obtain a file descriptor for
the file object corresponding to an event you can use the
struct file_handle that's provided within the
fanotify_event_info_fid in conjunction with the
open_by_handle_at(2) system call. A check for ESTALE is
done to accommodate for the situation where the file handle
for the object was deleted prior to this system call. */
event_fd = open_by_handle_at(mount_fd, file_handle, O_RDONLY);
if (event_fd == -1) {
if (errno == ESTALE) {
printf("File handle is no longer valid. "
"File has been deleted\n");
continue;
} else {
perror("open_by_handle_at");
exit(EXIT_FAILURE);
}
}
snprintf(procfd_path, sizeof(procfd_path), "/proc/self/fd/%d",
event_fd);
/* Retrieve and print the path of the modified dentry. */
path_len = readlink(procfd_path, path, sizeof(path) - 1);
if (path_len == -1) {
perror("readlink");
exit(EXIT_FAILURE);
}
path[path_len] = '\0';
printf("\tDirectory '%s' has been modified.\n", path);
if (file_name) {
ret = fstatat(event_fd, file_name, &sb, 0);
if (ret == -1) {
if (errno != ENOENT) {
perror("fstatat");
exit(EXIT_FAILURE);
}
printf("\tEntry '%s' does not exist.\n", file_name);
} else if ((sb.st_mode & S_IFMT) == S_IFDIR) {
printf("\tEntry '%s' is a subdirectory.\n", file_name);
} else {
printf("\tEntry '%s' is not a subdirectory.\n",
file_name);
}
}
/* Close associated file descriptor for this event. */
close(event_fd);
}
printf("All events processed successfully. Program exiting.\n");
exit(EXIT_SUCCESS);
}
okay that's the whole program bestie, and it ATE ๐
โจ look at it looping through events with FAN_EVENT_OK() and FAN_EVENT_NEXT(), being all responsible about the ESTALE case (because yeah, a file can be gone before you get to it ๐ญ), turning the event fd into a real path through /proc/self/fd, and then fstatat()-ing the entry name to find out if it's a directory or not. and it closes every fd it opens, because we do not leak fds in this house ๐ซถ
๐ฆ SEE ALSO ๐ฆ
like literally go read these next, they're the whole friend group:
and that's the tea, the whole page, every last byte of it ๐ this masterpiece lives in Linux man-pages 6.20, dated 2026-02-14 โ screenshot it, cite it, love it, it's iconic ๐๐
๐ฆ where this page comes from
- arch rolling: man-pages 6.20-1 ยท BSD-2-Clause AND BSD-3-Clause AND BSD-4.3TAHOE AND BSD-4-Clause-UC AND GPL-1.0-or-later AND GPL-2.0-only AND GPL-2.0-or-later AND GPL-3.0-or-later AND LGPL-3.0-linking-exception AND LGPL-3.0-or-later AND LicenseRef-Public-Domain AND LicenseRef-UltraPermissive AND Linux-man-pages-1-para AND Linux-man-pages-copyleft AND Linux-man-pages-copyleft-2-para AND Linux-man-pages-copyleft-var AND MIT AND Spencer-94
- nixpkgs unstable: man-pages 6.20
- ๐ the page's license: Linux-man-pages-copyleft
- Copyright 2014, Michael Kerrisk <mtk.manpages@gmail.com>
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms