Course contentsShow
← Linux
Lesson 313 of 1,8193. The Filesystem Hierarchy and POSIX StandardsFree lesson

The Lifecycle of Temporary Mounts

Automate the lifecycle of removable media and network mounts using hotplug daemons.

In this lesson, you will learn how to automate the lifecycle of removable media and network mounts using hotplug daemons.

So far, we have discussed manual mounting and filesystem consistency. However, constantly running mount and umount commands for USB drives or network shares is tedious and prone to error. In Linux, we delegate this task to a hotplug daemon, such as udev.

A hotplug daemon acts as an event listener. When you plug in a USB drive, the kernel emits an event. The daemon catches this event, identifies the device, and executes a script to handle the mounting process. This transforms a manual, error-prone task into a seamless lifecycle managed by the system.

The Lifecycle Workflow

  1. Detection: The kernel notifies the daemon that a block device exists.
  2. Triggering: The daemon matches the device against predefined rules (e.g., serial number or filesystem type).
  3. Mounting: The daemon executes a mount command, often creating a directory in /media or /mnt dynamically.
  4. Monitoring: The daemon watches for a "remove" event.
  5. Unmounting: Upon disconnection, the daemon ensures the filesystem is synced and unmounted safely, preventing data corruption.

For example, a udev rule might look like this:

ACTION=="add", SUBSYSTEM=="block", ENV{ID_FS_LABEL}=="MY_USB", RUN+="/usr/local/bin/automount.sh %k"
ACTION=="remove", SUBSYSTEM=="block", ENV{ID_FS_LABEL}=="MY_USB", RUN+="/usr/local/bin/autounmount.sh %k"

In this configuration, %k is a placeholder for the device name (like sdb1). When the event triggers, your script handles the directory creation and mounting logic, effectively automating the entire existence of that mount point from the moment of connection to the moment of removal. By automating this via the daemon, you ensure that even if the device is pulled out unexpectedly, the system state remains consistent, and you avoid dangling mounts that could block future operations.

Key Takeaway: Hotplug daemons automate the mounting and unmounting lifecycle by listening for kernel events, ensuring removable media is consistently managed without manual intervention.