Skip to content
masdzub.com
~/articles/linux — one from the notebook

Resolving Linux Disk Space Discrepancies: Finding Undeleted Open File Handles with lsof

Diagnose and fix Linux filesystem discrepancy where df reports a full disk while du shows free space using lsof and the proc filesystem.

masdzub@website:~$ cat ~/articles/linux-disk-full-but-df-shows-free-space-finding-undeleted-file-handles-with-lsof.aspx.md
# 1 file · 24 min read · topic: linux · status: published

Introduction

A Linux filesystem reports one hundred percent capacity in df -h, yet calculating used space with du -sh reveals gigabytes of unallocated storage. This specific condition occurs when a running process retains an active file descriptor to a file that was deleted from the filesystem namespace. The POSIX standard dictates that unlinking a directory entry removes only the pointer from the directory structure, while the underlying inode and data blocks remain allocated until the last process closes the file handle.

+-----------------------------------------------------------------------+
| DIRECTORY ENTRY (Namespace) INODE & DATA BLOCKS (Storage) |
| /var/log/app/output.log --unlink()--> [ Inode: 412891, Links: 0 ] |
| (Deleted from directory tree) | |
| | Ref Count: 1 |
| v |
| RUNNING PROCESS (PID 21458) [ 85 GB Allocated Data Blocks ] |
| Open File Descriptor 3 ------------> Blocks retained on disk until |
| PID exits or FD is truncated |
+-----------------------------------------------------------------------+

When an engineer or an automated log cleanup cron job executes rm against an active log file, the filename disappears from the directory tree. Tools like du (disk usage) rely on traversing directory paths via readdir() and issuing stat() or lstat() syscalls on each discovered node. Because the unlinked file is missing from the directory tree, du skips it entirely and reports low disk utilization. Conversely, df (disk free) issues the statvfs() syscall against the filesystem mount point, querying the superblock for absolute counts of allocated blocks and free block bitmaps. The superblock tracks all allocated data blocks regardless of whether they possess directory entries.

This discrepancy halts production services when write operations fail with ENOSPC (No space left on device), despite apparent free space during manual inspection. Resolving this issue requires locating the processes holding orphaned file handles using lsof or the /proc filesystem, then reclaiming storage space without restarting mission-critical workloads.


To resolve open file handle issues systematically, you must understand how UNIX and Linux kernels decouple namespace addressing from physical storage blocks on disk.

Every regular file inside an ext4, XFS, or similar UNIX filesystem consists of three distinct components:

  1. The directory entry (dentry), which maps an arbitrary human-readable string to an integer inode number.
  2. The inode data structure, which stores metadata including ownership, permissions, timestamps, link counts (i_nlink), and pointers to data extents.
  3. The data blocks, which reside on the underlying block device containing the payload bytes.
+------------------+ +-------------------------------+
| Directory Entry | | Inode |
| Name: server.log | ------> | Number: 1048576 |
| Inode: 1048576 | | Links (i_nlink): 1 |
+------------------+ | Size: 48 GB |
| Pointers to blocks: [Extents] |
|
v
+-------------------------------+
| Data Blocks |
| [Block 5001] ... [Block 9800] |
+-------------------------------+

When a process opens a file using the open() system call with flags such as O_WRONLY or O_RDWR, the kernel verifies permissions, allocates an entry in the system-wide open file table, and returns a non-negative integer representing the file descriptor (FD) to the calling process. The kernel increments an internal in-memory reference counter for that open file description.

Executing the rm utility does not invoke a destructive “delete” system call. Linux provides no delete() syscall for regular files. The rm command invokes unlink(). The unlink() syscall decrements the hard link counter (i_nlink) stored inside the inode. If other hard links point to that same inode, the file remains fully accessible through those alternate names. When the link count reaches zero, the directory entry is unlinked and removed from the parent directory’s hash tree or linear table.

However, the storage driver does not return the allocated data blocks to the filesystem free block bitmap immediately. The kernel checks two distinct conditions before freeing blocks:

  1. The on-disk link counter i_nlink must equal zero.
  2. The in-kernel open file reference counter must equal zero.

If a long-running process like Java, Python, or an NGINX worker holds an active file descriptor pointing to an inode whose i_nlink is zero, the blocks remain allocated. The filesystem marks those blocks as reserved. The operating system prevents any other file or process from overwriting that disk space to protect the integrity of the running process. The data blocks are deallocated only after the process closes the descriptor via close() or terminates completely.


The System Call Divergence: statvfs() Versus stat()

The root of administrative confusion during an ENOSPC incident stems from the operational divergence between df and du.

================================================================================
df Command Architecture
================================================================================
User Space: df -h /var/log
|
Kernel: sys_statvfs() / statfs()
|
Superblock: Reads total_blocks, free_blocks, available_blocks from disk superblock
Result: Accurate block utilization, counts unlinked open files
================================================================================
================================================================================
du Command Architecture
================================================================================
User Space: du -sh /var/log
|
Directory: openat(), getdents64() (Directory Traversal)
|
Kernel: sys_newstat() / sys_lstat() on each discovered directory entry
Result: Inaccurate for unlinked files; cannot traverse what has no filename
================================================================================

The df utility operates at the filesystem layer. It takes a target path, determines the backing mount point, and issues the statfs() or statvfs() system call.

#include <sys/statvfs.h>
struct statvfs buf;
statvfs("/var", &buf);
// Total blocks: buf.f_blocks
// Free blocks: buf.f_bfree
// Available: buf.f_bavail

The superblock maintains a global tally of free blocks and inodes. Whenever an application writes a 4 KB page to disk, the kernel filesystem driver updates the allocation trees (such as extent allocation trees in XFS or block bitmaps in ext4) and decrements the superblock’s free block counter. Because the unlinked file is still consuming actual storage blocks, the superblock correctly reflects that this space is in use.

The du utility operates at the namespace layer. It begins at a root path and initiates recursive traversal using openat() and getdents64(). For every directory entry returned, it issues an lstat() system call to determine the file size and block count:

#include <sys/stat.h>
struct stat statbuf;
lstat("/var/log/syslog", &statbuf);
// Blocks allocated: statbuf.st_blocks

Because an unlinked file has no directory entry, the getdents64() system call never returns its inode number to du. The recursive descent passes over the space consumed by the phantom file. The aggregate sum printed by du will be lower than the space reported by df.

When df indicates 98% usage on /var and du /var sums up to only 12 GB out of 100 GB, you are dealing with unlinked file descriptors holding onto the missing 86 GB.


Identifying Open Unlinked Files Using lsof

The primary administrative tool for identifying orphaned file descriptors is lsof (List Open Files). It inspects the kernel state exposed via /proc and system structures to correlate processes with open files, network sockets, pipes, and devices.

To list all files held open by running processes that have been unlinked from the directory tree, run:

Terminal window
lsof +L1

The parameter +L1 instructs lsof to filter results for files with a hard link count strictly less than 1. This isolates unlinked files.

COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
dockerd 1102 root 19u REG 8,1 53687091200 4194308 /var/lib/docker/overlay2/merged/var/log/app.log (deleted)
java 15822 app 12w REG 8,1 32212254720 4194315 /opt/tomcat/logs/catalina.out (deleted)
python3 29401 root 4w REG 8,1 12884901888 4194320 /var/log/worker.log (deleted)

In standard output, look for the following fields:

  • COMMAND: The binary name associated with the process.
  • PID: The process identification number.
  • USER: The system user running the binary.
  • FD: The file descriptor number, accompanied by the access mode. In the output above, 19u signifies file descriptor 19 opened for read/write (u), while 12w signifies file descriptor 12 opened in write-only (w) mode.
  • DEVICE: The major and minor device numbers pointing to the physical or logical block device (for example, 8,1 maps to /dev/sda1).
  • SIZE/OFF: The size of the file in bytes, or the current offset pointer.
  • NODE: The filesystem inode number.
  • NAME: The original path string followed by the indicator (deleted).

Targeting Specific Mount Points and Sorting Output

In production servers with thousands of threads, lsof +L1 can generate excessive output. You can constrain the query to the specific mount point experiencing disk exhaustion:

Terminal window
lsof +L1 /var

To isolate the top storage consumers holding deleted files, combine lsof with awk, sort, and head. The following pipeline isolates deleted files, sorts them numerically by their byte size, and prints the top culprits in human-readable formatting:

Terminal window
lsof -nP +L1 /var | awk '{
if ($5 == "REG" && $10 ~ /\(deleted\)/) {
printf "%-10s %-8s %-6s %12.2f MB %s\n", $1, $2, $4, $7/(1024*1024), $9
}
}' | sort -k4 -nr | head -n 20

Breaking down the options passed to lsof:

  • -n: Inhibits conversion of network IP addresses to hostnames, preventing network timeouts from hanging the diagnostic command.
  • -P: Inhibits conversion of port numbers to service names, lowering execution overhead.
  • +L1: Restricts results to files with a link count of zero.

Direct Kernel Inspection via the /proc Filesystem

When lsof is not installed on a hardened container, minimal Linux distribution, or recovery environment, you can query kernel state through /proc.

The /proc virtual filesystem provides an interface to internal kernel data structures. For every process on the system, the directory /proc/[PID]/fd/ contains symbolic links representing every open file descriptor.

/proc/15822/fd/
├── 0 -> /dev/null
├── 1 -> /opt/tomcat/logs/catalina.out (deleted)
├── 2 -> /opt/tomcat/logs/catalina.out (deleted)
├── 3 -> socket:[981245]
└── 4 -> anon_inode:[eventpoll]

When an open file is unlinked, the Linux virtual file system (VFS) appends the literal string (deleted) to the target of the symlink inside /proc/[PID]/fd/.

Locating Unlinked Descriptors Using bash and find

You can traverse all active process file descriptors using find:

Terminal window
find /proc/[0-9]*/fd/ -type l -lname '* (deleted)*' 2>/dev/null

This returns a list of matching descriptors:

/proc/15822/fd/1
/proc/15822/fd/2
/proc/29401/fd/4

To extract meaningful metrics like PID, process name, descriptor ID, and byte size, run this one-line shell script:

Terminal window
for link in $(find /proc/[0-9]*/fd/ -type l -lname '* (deleted)*' 2>/dev/null); do
target=$(readlink "$link")
if [[ "$target" =~ ^/.*\(deleted\)$ ]]; then
pid=$(echo "$link" | cut -d/ -f3)
fd=$(echo "$link" | cut -d/ -f5)
cmd=$(cat "/proc/$pid/comm" 2>/dev/null || echo "unknown")
# Read the size of the referenced file via stat on the fd symlink
size_bytes=$(stat -L -c %s "$link" 2>/dev/null || echo 0)
if [ "$size_bytes" -gt 104857600 ]; then # Filter entries > 100MB
size_mb=$((size_bytes / 1024 / 1024))
echo "PID: $pid ($cmd) | FD: $fd | Size: ${size_mb}MB | Target: $target"
fi
fi
done | sort -t: -k4 -nr

This inspection runs natively on any Linux distribution using standard coreutils, without external dependencies.


Safe Space Reclamation Without Restarting Services

The default reaction to finding a large deleted file handle is restarting the parent process. In a production cluster running an enterprise database, an API gateway, or an in-memory queue, restarting a service can cause request drops, secondary failovers, or extended cache rebuilds.

You can safely reclaim the trapped storage space while the application remains running.

================================================================================
The Truncation Remedy
================================================================================
Application PID 15822 (catalina.out open on FD 12, size: 32 GB)
|
|-- DO NOT: kill -9 15822 (Causes downtime, dropped connections)
|-- DO NOT: rm -f /opt/tomcat/logs/catalina.out (Already gone, no effect)
|
+-> EXECUTE: : > /proc/15822/fd/12
|
v
Kernel intercepts redirect, triggers truncate() logic
Allocated extents zeroed in block bitmap
Disk space frees instantly; PID 15822 continues running safely
================================================================================

The Ineffectiveness of rm

Executing rm against a file that is already marked (deleted) does nothing:

Terminal window
rm -f /opt/tomcat/logs/catalina.out
# Output: No such file or directory (or silent exit, but 0 bytes freed)

Because the dentry is already gone, rm cannot reach the inode. The path does not exist in the root namespace.

Truncating the File Descriptor via /proc

Every entry in /proc/[PID]/fd/[FD] is a symlink pointing to the file. If the file was opened with write privileges (w or u), writing to this symlink passes directly to the underlying file description in the kernel.

Using the shell redirection operator >, you can truncate the file length to zero bytes:

Terminal window
: > /proc/15822/fd/12

Alternatively, use the truncate command:

Terminal window
truncate -s 0 /proc/15822/fd/12

The shell opens /proc/15822/fd/12 using the O_TRUNC flag. The kernel intercepts the operation and invokes the filesystem driver’s truncate routine. The driver traverses the inode’s block pointers, unallocates all data extents, returns the blocks to the free block bitmap, and resets the file size attribute to 0.

Verify the reclaimed space immediately with df:

Terminal window
df -h /var

The used space drops instantly, without the process crashing or dropping network sockets.

Caveats with Write Modes and Append-Only Operations

Before truncating, inspect the permissions mode reported by lsof or /proc/[PID]/fdinfo/[FD].

Check the descriptor access mode:

Terminal window
cat /proc/15822/fdinfo/12

Typical output:

pos: 34587645120
flags: 0100001
mnt_id: 28
ino: 4194315

The flags field contains the octal representation of the file status flags passed during the open() call (defined in <fcntl.h>).

Important flag values:

  • 01: O_WRONLY (Write-only)
  • 02: O_RDWR (Read-Write)
  • 02000: O_APPEND (Append mode)

If the target process was opened with O_WRONLY without O_APPEND, the process maintains an internal write pointer in its own runtime memory space (or relies on the kernel pos value). When you truncate the file, the file size becomes zero. However, if the application continues writing at its existing file offset (for example, offset 34587645120), the filesystem creates a sparse file.

In a sparse file, the initial 34 GB will contain unallocated null bytes (holes) that consume zero physical storage blocks on the physical drive, and only newly written bytes allocate actual storage blocks. However, future operations that read the file sequentially might misinterpret these sparse holes. For logging processes, modern loggers use O_APPEND. With O_APPEND, the kernel forces the write offset to the current end of the file before every write operation. Truncating an append-mode descriptor allows the application to continue logging from offset 0 without losing writes.


Edge Case Scenarios in Production Environments

In real-world environments, unlinked file handles often interact with container abstraction layers, network mounts, and journal sub-systems.

1. Docker and Containerd OverlayFS Storage Exhaustion

In containerized environments running on Docker or Kubernetes, a container can run out of disk space on the host storage pool (/var/lib/docker/overlay2/) due to an unlinked file handle inside a container namespace.

+-------------------------------------------------------------------+
| HOST SYSTEM (Root Filesystem /) |
| /var/lib/docker/overlay2/abcdef123456/merged |
| |
| +-------------------------------------------------------------+ |
| | CONTAINER NAMESPACE (PID 4812 inside host, PID 1 inside cgroup)|
| | /app/logs/production.log (Deleted inside container) |
| | Inode retained on host backing store |
| +-------------------------------------------------------------+ |
+-------------------------------------------------------------------+

When you run lsof +L1 on the host, the reported path displays the full path through the host’s OverlayFS mount:

COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
node 4812 1000 9w REG 253,1 84291840000 8912384 /var/lib/docker/overlay2/e8f9b.../merged/app/logs/production.log (deleted)

To resolve this without stopping the container:

  1. Locate the PID on the host system (PID 4812).
  2. Trace into the descriptor link:
    Terminal window
    : > /proc/4812/fd/9
  3. Alternatively, enter the container’s mount namespace using nsenter:
    Terminal window
    nsenter -t 4812 -m -p, truncate -s 0 /proc/1/fd/9

2. Network Filesystems and the NFS Silly Rename Behavior

When an application deletes a file that another process on a different NFS client maintains open, the NFS client protocol cannot drop the file completely. NFS is inherently a stateless file access protocol.

To maintain POSIX compliance for open file descriptors across network shares, the Linux NFS client implements a mechanism known as silly rename.

Instead of issuing an NFS_REMOVE RPC call over the wire, the kernel catches the unlink() call and executes an NFS_RENAME operation, converting the file into a hidden file named .nfsXXXX (where XXXX represents a hexadecimal inode sequence).

Terminal window
ls -la /mnt/nfs/data/
drwxr-xr-x 2 app app 4096 Nov 27 08:30 .
drwxr-xr-x 8 app app 4096 Nov 27 08:00 ..
-rw-r--r-- 1 app app 42949672960 Nov 27 09:12 .nfs0000000000412a81

Unlike local filesystems, these files are visible to du. If an engineer tries to delete the .nfsXXXX file directly:

Terminal window
rm -f /mnt/nfs/data/.nfs0000000000412a81
# Result: Device or resource busy (EBUSY)

The Linux kernel explicitly blocks the unlinking of an active silly-renamed file, returning error code EBUSY.

To clear an .nfs orphan:

  1. Find the local or remote process holding the descriptor:
    Terminal window
    lsof /mnt/nfs/data/.nfs0000000000412a81
  2. If the PID is local, truncate via /proc/[PID]/fd/[FD]. Once the holding process closes the descriptor, the NFS client sends the actual NFS_REMOVE RPC automatically, cleaning up the .nfsXXXX entry from the remote storage server.

3. Logrotate Misconfigurations

A common cause of unlinked file leaks is an incorrect logrotate configuration script.

Consider this invalid configuration:

/var/log/custom-app/*.log {
daily
rotate 7
compress
missingok
notifempty
}

By default, logrotate renames the file (for example, from app.log to app.log.1), then compresses it via gzip. The compression utility reads app.log.1, writes app.log.1.gz, and then unlinks app.log.1.

If the application writing to app.log does not close and reopen its file handle, it continues writing to the unlinked app.log.1 inode. The active log volume expands rapidly, hidden from standard directory listings.

To fix this, you must instruct the application to release its descriptor using one of two strategies:

Strategy A: Use copytruncate

/var/log/custom-app/*.log {
daily
rotate 7
copytruncate
compress
}

copytruncate copies the active file contents to a secondary backup file, then truncates the original file in-place using truncate(). The process never loses its original descriptor reference, and no inode pointers are broken.

Strategy B: Send a reload signal via postrotate

/var/log/custom-app/*.log {
daily
rotate 7
compress
postrotate
/bin/kill -HUP $(cat /var/run/custom-app.pid 2>/dev/null) 2>/dev/null || true
endscript
}

Sending SIGHUP instructs applications like NGINX or rsyslog to close their current file handles and call open() again on the default path, creating a fresh file on disk.


Filesystem Specifics: ext4, XFS, and Btrfs

Different Linux filesystems handle block tracking, allocations, and reserved margins uniquely during capacity exhaustion.

FilesystemBehavior on Unlink with Open DescriptorsReserved Space MechanismInode Allocation Method
ext4Blocks remain allocated in block bitmap; space freed instantly upon truncation or descriptor closure.Reserves 5% for root user by default (configurable via tune2fs -m).Fixed allocation at format time (mkfs.ext4 -N). Inodes can exhaust before disk blocks.
XFSManaged via delayed logging and extent free lists. Unlinked inodes placed in per-AG unlinked lists.Dynamic reserve pool; no fixed 5% root block reservation.Dynamic inode allocation across Allocation Groups (AGs).
BtrfsSpace remains locked in subvolume tree; reference counts tracked across generation roots.Enforces minimum metadata reservation space. Truncating large files can fail if metadata tree cannot update.Dynamic inode allocation. Copy-on-Write (CoW) causes space to rise during deletions.

The ext4 Reserved Block Allocation

On ext4 filesystems, five percent of total storage space is reserved for the root user by default. If a normal system user process fills the partition with deleted file handles, non-privileged applications receive ENOSPC when the volume hits ninety-five percent capacity:

$ echo "test" >> /home/user/test.txt
-bash: echo: write error: No space left on device

At the same time, root administrative commands continue to work, allowing systems operators to log in over SSH, investigate with lsof, and complete remediations without the system locking up entirely.

You can inspect the reserved blocks using tune2fs:

Terminal window
tune2fs -l /dev/sda1 | grep -E "Block count|Reserved block count"
Block count: 26214400
Reserved block count: 1310720

To temporarily reduce this reservation from five percent to one percent during an emergency to allow services to recover, run:

Terminal window
tune2fs -m 1 /dev/sda1

XFS Unlinked List Tracking

XFS handles unlinked files by organizing them into unlinked lists inside its per-allocation-group (AG) headers.

When an application unlinks an open file in XFS:

  1. The inode is added to an internal linked list (agi->agi_unlinked[]).
  2. If the operating system crashes or power fails before the file descriptor is closed, the XFS recovery log processes this list during the next mount cycle.
  3. During journal replay, the kernel walks the agi_unlinked chains and cleans up the orphaned data extents, preventing hidden block leaks from corrupting the filesystem balance across reboots.

Step-by-Step Incident Playbook: Production Outage

Here is a reproducible walk-through showing how to diagnose and resolve an unlinked file handle leak during an on-call emergency.

Step 1: Detect the Discrepancy

Monitor alerts indicate that the /var mount is at 100% capacity:

Terminal window
df -h /var
Filesystem Size Used Avail Use% Mounted on
/dev/sdb1 50G 50G 0 100% /var

Calculate the aggregate directory size:

Terminal window
du -sh /var 2>/dev/null
12G /var

The discrepancy between 50 GB (df) and 12 GB (du) confirms that 38 GB of storage space is held hostage by unlinked open file handles.

Step 2: Identify the Responsible Process

Search for all open unlinked files on the /var filesystem using lsof:

Terminal window
lsof +L1 /var
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
supervisord 841 root 3w REG 8,17 40802189312 9182 /var/log/supervisord.log (deleted)

The output reveals that supervisord (PID 841) holds open file descriptor 3, pointing to an unlinked log file consuming approximately 40.8 GB.

Step 3: Verify the Descriptor in /proc

Confirm the file descriptor status in the /proc filesystem:

Terminal window
ls -l /proc/841/fd/3
l-wx------ 1 root root 64 Nov 27 09:30 /proc/841/fd/3 -> /var/log/supervisord.log (deleted)

Check the process details:

Terminal window
ps -p 841 -o pid,user,args
PID USER COMMAND
841 root /usr/bin/python3 /usr/bin/supervisord -n -c /etc/supervisor/supervisord.conf

Step 4: Reclaim the Space Safely

Truncate the file descriptor to zero bytes via the proc filesystem:

Terminal window
: > /proc/841/fd/3

If the shell returns Permission denied, ensure you are operating as the root user or using sudo with a shell invocation:

Terminal window
sudo sh -c ': > /proc/841/fd/3'

Step 5: Validate Resolution

Check the filesystem utilization with df:

Terminal window
df -h /var
Filesystem Size Used Avail Use% Mounted on
/dev/sdb1 50G 12G 38G 24% /var

The available space jumps back to 38 GB immediately. The system drops from 100% usage to 24% without restarting the supervisor process or interrupting its managed child processes.


Troubleshooting Common Errors and Failures

During emergency remediations, you may encounter system errors when attempting to clear file handles.

Error 1: “bash: /proc/PID/fd/X: Permission denied”

This error occurs when attempting to redirect output into a file descriptor owned by another security context or user:

Terminal window
$ sudo echo "" > /proc/15822/fd/12
bash: /proc/15822/fd/12: Permission denied

Root cause: The sudo binary grants elevated privileges to echo, but the output redirection (>) is evaluated by your current unprivileged shell before sudo executes.

Fix: Run the shell itself within the elevated context:

Terminal window
sudo bash -c ': > /proc/15822/fd/12'

If the error persists under a root shell, check the file access flags:

Terminal window
cat /proc/15822/fdinfo/12 | grep flags

If the flags indicate O_RDONLY (flag 00), you cannot truncate the descriptor. The kernel prevents opening a read-only descriptor for writing. In this scenario, you must send a signal to the process to close the handle, or restart the process.

Error 2: “lsof: WARNING: can’t stat() fuse.gvfsd-fuse file system”

When executing lsof, the utility may hang or output warnings regarding FUSE mounts:

lsof: WARNING: can't stat() fuse.gvfsd-fuse file system => /run/user/1000/gvfs
Output information may be incomplete.

Root cause: A FUSE daemon belonging to a user desktop session is unmounted uncleanly or unresponsive, blocking system calls from other users.

Fix: Instruct lsof to avoid crossing filesystem boundaries or explicitly skip FUSE filesystems:

Terminal window
lsof -b +L1 /var

The -b flag avoids kernel functions that could block on unresponsive network or user-space filesystems.

Error 3: Space Not Freeing After Truncation

You executed : > /proc/PID/fd/X, but df shows no drop in utilized storage.

Possible reasons:

  1. Multiple file descriptors reference the same file. Check if other descriptors or child processes inherited the handle across a fork() call:

    Terminal window
    lsof +L1 | grep "4194315" # Search by inode number, not filename

    If worker child processes inherited the descriptor, each process holds its own pointer to the same inode. You must truncate the descriptor in every PID that holds it open, or restart the process group.

  2. The application uses memory-mapped files (mmap). If an application allocates disk space via fallocate() and maps it into virtual address spaces using mmap(), the blocks are pinned by the virtual memory subsystem. Truncating the file descriptor symlink does not unmap the virtual memory pages. In this case, you must terminate the process to free the memory-mapped blocks.

Terminal window
# Check if the process has active memory mappings to unlinked files
grep "(deleted)" /proc/15822/maps

Output:

7f9b8c000000-7f9b90000000 rw-s 00000000 08:01 4194315 /var/log/app.dat (deleted)

If /proc/PID/maps contains an active reference, terminating the process is required:

Terminal window
kill -TERM 15822

Defensive Engineering: Proactive Monitoring and Auditing

To prevent unlinked files from causing production outages, incorporate proactive detection into your monitoring architecture.

Monitoring via Prometheus node_exporter

The standard Prometheus node_exporter does not track unlinked open file handle sizes out of the box because walking /proc on systems with tens of thousands of threads creates high CPU overhead.

You can implement a custom textfile collector script to audit this metric safely. Place the following script in /etc/cron.d/audit_deleted_files:

/usr/local/bin/collect_deleted_fd_bytes.sh
#!/usr/bin/env bash
set -euo pipefail
METRIC_FILE="/var/lib/node_exporter/textfile_collector/deleted_fd_space.prom"
TMP_FILE="${METRIC_FILE}.tmp"
# Aggregate total bytes held by deleted files on each mount
TOTAL_DELETED_BYTES=$(find /proc/[0-9]*/fd/ -type l -lname '* (deleted)*' 2>/dev/null | while read -r link; do
stat -L -c %s "$link" 2>/dev/null || echo 0
done | awk '{s+=$1} END {print s+0}')
cat <<EOF > "$TMP_FILE"
# HELP node_filesystem_deleted_file_bytes Total bytes retained by unlinked open file handles
# TYPE node_filesystem_deleted_file_bytes gauge
node_filesystem_deleted_file_bytes ${TOTAL_DELETED_BYTES}
EOF
mv "$TMP_FILE" "$METRIC_FILE"

Add a Prometheus alerting rule in Alertmanager to catch leaks early:

groups:
- name: storage_alerts
rules:
- alert: HighDeletedFileHandleSpace
expr: node_filesystem_deleted_file_bytes > 10737418240 # Greater than 10 GB
for: 15m
labels:
severity: warning
annotations:
summary: "Host has over 10GB of orphaned storage held by open file descriptors"
description: "Instance {{ $labels.instance }} has {{ $value | humanize1024 }}B held by deleted files. Run 'lsof +L1' to remediate."

Implementing Audit Rules with auditd

To identify rogue scripts or services deleting log files instead of using log rotation protocols, configure the Linux Audit daemon (auditd).

Add an audit rule targeting the unlink and unlinkat system calls within the log directory:

Terminal window
auditctl -a always,exit -F arch=b64 -S unlink -S unlinkat -F dir=/var/log/ -k log_cleanup

Review the audit logs when an unexpected file deletion occurs:

Terminal window
ausearch -k log_cleanup --raw | aureport -u -i

This output reveals the command, system user, and executable binary responsible for unlinking files, helping you track down misbehaving scripts before they cause a disk-full incident.


Comparative Reference: lsof and /proc Commands

The following table provides quick reference commands for diagnosing and remediating deleted file handles during an incident.

ObjectiveCommandNotes
Find all deleted files on all mountslsof +L1Can be slow on busy servers with high thread counts.
Target a specific mount pointlsof -nP +L1 /varSkips DNS and port resolution for fast results.
Sort top 10 files by byte sizelsof -nP +L1 /var | sort -k7 -nr | head -n 10Uses column 7 (file size in bytes).
Inspect via native shell (no lsof)find /proc/[0-9]*/fd/ -type l -lname '* (deleted)*'Works on minimal Docker images and recovery shells.
Check file descriptor access flagscat /proc/<PID>/fdinfo/<FD>Look for flags: 01 (write) or flags: 02 (read/write).
Truncate descriptor in-place: > /proc/<PID>/fd/<FD>Instantly reclaims blocks without killing the process.
Verify reclaimed disk spacedf -h <mountpoint>Superblock free block counter updates immediately.
Check memory mappings to deleted filesgrep "(deleted)" /proc/<PID>/mapsIf present, process must be restarted to free memory.
found this useful? share it →
Written by

Dzubayyan Ahmad

System Administrator, SRE & Technical Support Engineer specialising in web hosting infrastructure — Linux servers, automation, and monitoring. Writing these notes since 2015 so future-me can find the fix again.