fanotify_init - Linux


Overview

fanotify_init is a system call used to create an instance of a file notification group, known as a fanout. This group serves as a central point for monitoring file system events, allowing applications to receive notifications when specific operations occur on designated files or directories. Fanotify is particularly useful for security monitoring, real-time file synchronization, backup applications, and maintaining file system integrity.

Syntax

fanotify_init(flags, event_f_flags, mark) -> fd

Required Arguments:

  • flags: Integer flags controlling fanout initialization.
  • event_f_flags: Integer flags governing the types of file system events to be monitored.

Optional Arguments:

  • mark: An arbitrary integer used to identify the fanout group. If omitted, a unique mark is automatically assigned.

Options/Flags

flags:

  • FAN_CLASS_PRE_CONTENT: Monitor events prior to data modifications.
  • FAN_CLASS_CONTENT: Monitor events involving data modifications.
  • FAN_CLASS_NOTIF: Monitor events related to file notifications.
  • FAN_CLOEXEC: Close the fanout descriptor when the process exits.
  • FAN_NONBLOCK: Make the fanout descriptor non-blocking.

event_f_flags:

  • FAN_ACCESS: File access (read or write)
  • FAN_MODIFY: File modification (change in data or metadata)
  • FAN_ATTRIB: File attribute changes (e.g., permissions, timestamps)
  • FAN_OPEN: File open
  • FAN_CLOSE_WRITE: File close after write
  • FAN_CLOSE_NOWRITE: File close without write
  • FAN_REMOVE: File deletion

Examples

Simple File Event Monitoring:

fd = fanotify_init(FAN_CLASS_PRE_CONTENT, FAN_OPEN, 0)

Monitoring Specific Directory:

dir_fd = os.open("/path/to/dir", os.O_RDONLY)
fd = fanotify_init(FAN_CLASS_PRE_CONTENT, FAN_OPEN, 0)
fanotify_mark(fd, FAN_MARK_ADD, dir_fd, FAN_OPEN)

Common Issues

  • Permission Denied: Ensure the user running the command has sufficient permissions to monitor the target file or directory.
  • Invalid Flags: Verify that the provided flags are valid and compatible.
  • File Descriptor Limit: The number of fanotify groups is limited by system resources. Exceeding this limit may result in failures.

Integration

  • inotifywait: Use fanotify with inotifywait to perform advanced file system event monitoring tasks.
  • logrotate: Integrate fanotify to monitor log file rotations and trigger appropriate actions.
  • Tripwire: Utilize fanotify for file integrity monitoring, notifying Tripwire of unauthorized changes.

Related Commands

  • fanotify_mark: Manage file notifications within a fanout group.
  • inotify: Monitor file system events using a different approach (event-based instead of group-based).