HANDS-ON LAB Beginner

Linux Disk Full but du Shows Free Space: Finding Unlinked Open Files & Logrotate

Locate files that were deleted but remain open by active processes using lsof +L1, safely truncate them, and configure logrotate.

Vibe DevOps·· ~10 min read
LinuxPython 3lsoflogrotatecoreutils

Key Takeaways & Prerequisites

  • Running rm on an active log file only removes its directory entry; the filesystem cannot free disk blocks until the holding process closes its file descriptor.
  • Discrepancies between df -h (disk space full) and du -sh (files sum up to small size) are definitive proof of unlinked open file descriptors.
  • Identify deleted open files instantly using lsof +L1 or grep -i deleted /proc/*/fd/.
  • Truncate active files safely using : > /proc/<PID>/fd/<FD> or configure logrotate with copytruncate / postrotate systemctl reload.

Architecture & Execution Flow

  1. 01 →df vs du DivergenceUnlinked open file descriptor detection
  2. 02 →Identify Culpritlsof +L1 and /proc/<PID>/fd
  3. 03 →Emergency TruncateTruncate via file descriptor directly
  4. 04 →Logrotate Hardeningpostrotate reload / copytruncate
Table of Contents

A midnight alert fires: the / root filesystem is at 98% utilization. The on-call engineer logs into the host, notices /var/log/app.log has grown to tens of gigabytes, and unceremoniously deletes it. Yet df still reports the disk as nearly full. Running du across the entire filesystem returns an aggregated usage substantially lower than what df reports. The consumed space has not disappeared—it remains held by an active process that still maintains an open file descriptor to the deleted file.

The root cause lies in how the Linux kernel manages files. rm invokes unlink() to detach the filename from the directory structure. Per unlink(2), if that was the last hard link to the file but any process still holds it open, the file continues to exist on disk until the final file descriptor referencing it is closed.[1] Because du traverses the directory hierarchy, it can no longer see the unlinked file. Conversely, df queries filesystem-level metadata (such as statvfs) and accounts for all blocks that have not yet been deallocated.

This lab reproduces that exact production failure mode using a log-generating Python process, then walks through three operational phases: identification, remediation, and prevention.

Scope: This lab runs entirely as an unprivileged user within an isolated directory, generates approximately 10–20 MB of logs, and touches no system services. All commands were validated on Ubuntu 22.04 with lsof 4.93.2 and logrotate 3.19.0. Production commands requiring sudo are segregated and explicitly marked. Review them carefully before running against live environments.

1. Prerequisites and Setup

You will need Linux, Python 3, lsof, logrotate, and GNU coreutils (df, du). On Debian/Ubuntu systems, install lsof and logrotate via apt if they are not already present. This lab requires no root privileges.

export LAB_DIR="$HOME/disk-lab"
mkdir -p "$LAB_DIR/logs"
cd "$LAB_DIR"
command -v python3 lsof logrotate df du

Create app_writer.py. This script simulates an application daemon that maintains an open handle to its log file throughout its runtime, writes approximately 512 KB per second, and reopens the log file upon receiving a SIGHUP signal. Many production daemons implement this exact behavior.

#!/usr/bin/env python3
"""Mock application: keeps log file open, writes steadily, reopens file on SIGHUP."""
import os
import signal
import time
from pathlib import Path

LAB = Path(os.environ.get("LAB_DIR", Path.home() / "disk-lab"))
LOG = LAB / "logs" / "app.log"
RATE_KB = int(os.environ.get("RATE_KB", "512"))  # KB per second
LOG.parent.mkdir(parents=True, exist_ok=True)
(LAB / "app.pid").write_text(f"{os.getpid()}\n")

reopen = False


def on_hup(signum, frame):
    global reopen
    reopen = True


def on_term(signum, frame):
    raise SystemExit(0)


signal.signal(signal.SIGHUP, on_hup)
signal.signal(signal.SIGTERM, on_term)

fh = open(LOG, "a", buffering=1)
payload = "x" * 1000
n = 0
while True:
    if reopen:
        fh.close()
        fh = open(LOG, "a", buffering=1)
        reopen = False
        fh.write(f"{int(time.time())} reopened log\n")
    for _ in range(RATE_KB):
        fh.write(f"{int(time.time())} req={n} {payload}\n")
        n += 1
    time.sleep(1)

Launch the application in a first terminal:

cd "$HOME/disk-lab"
LAB_DIR="$HOME/disk-lab" RATE_KB=512 python3 app_writer.py

Execute all subsequent steps from a second terminal.

2. Reproduction: Deleting an Open File Without Reclaiming Space

export LAB_DIR="$HOME/disk-lab"
PID="$(cat "$LAB_DIR/app.pid")"
du -sh "$LAB_DIR/logs"
rm "$LAB_DIR/logs/app.log"
sleep 2
du -sh "$LAB_DIR/logs"
ls -l "$LAB_DIR/logs"

Following rm, du drops to near zero and ls no longer shows app.log. However, the process continues appending to the original inode, causing it to consume more disk space over time. On a production partition near capacity, this is the point where df stops decreasing and instead continues to climb.

Because this lab only writes a few megabytes, the delta will not visibly affect df on a large disk. On a live server, cross-reference these two perspectives before drawing conclusions:

df -h /
df -i /
sudo du -xh --max-depth=1 / 2>/dev/null | sort -h | tail -15

df -i inspects inode utilization. A filesystem can exhaust its inode table despite having hundreds of gigabytes of free block capacity—a common symptom of micro-file accumulation (such as session caches or mail queues). The -x flag passed to du restricts the traversal to a single filesystem boundary.[2] This prevents virtual filesystems like /proc or remote mounts (NFS/EFS) from skewing directory size calculations. If du aggregates to substantially less than df, the primary suspect is unlinked files that are still held open by running processes. A secondary, rarer possibility is data hidden beneath an active mount point.

3. Identifying Deleted Files Held by Active Processes

The lsof utility provides the +L1 flag to list open files with a link count of less than 1, meaning they have been unlinked from the directory tree. Specifying +aL1 <filesystem> restricts the query to a specific mount point.[3] Within the lab environment, add -a -p to filter exclusively for our process. Omitting -a causes lsof to treat flags as logical OR conditions, outputting matching files across every process on the host.

lsof -nP -a +L1 -p "$PID"

The NLINK column reads 0, the NAME column displays a (deleted) suffix, and the FD column identifies the specific file descriptor—for example, 3w denotes file descriptor 3 opened for writing.

If lsof is unavailable on the target system, you can inspect /proc directly. Each entry under /proc/<pid>/fd is a symbolic link pointing to the underlying opened file.[4]

find "/proc/$PID/fd" -lname '*(deleted)' -printf '%p -> %l\n'
FD="$(find "/proc/$PID/fd" -lname "$LAB_DIR/logs/app.log (deleted)" -printf '%f\n')"
echo "FD=$FD"
stat -L -c 'size=%s bytes' "/proc/$PID/fd/$FD"

On a production host (read-only, requires sudo): query the entire root filesystem and aggregate the total disk space held by unlinked handles. The awk pipeline sums column 7 (SIZE/OFF) from default lsof output:

sudo lsof -nP +aL1 /
sudo lsof -nP +aL1 / | awk 'NR>1 {s+=$7} END {printf "%.1f MiB\n", s/1048576}'

On desktop environments or workstations running browsers, this command will output numerous small memfd instances or temporary browser files. This is standard operational behavior. Focus your triage on large entries—specifically application logs, database scratch tables, or unlinked core dumps.

4. Remediation: Safe Space Reclamation Strategies

Evaluate remediation options using the following priority hierarchy:

Method When to Use Implications
Application log reopen (SIGHUP, reopen command) Supported by the application Zero log loss, zero downtime
Service restart No reopen mechanism available Brief service interruption, requires health check validation
Truncate file via /proc/<pid>/fd Emergency mitigation (approaching 100% disk utilization) Immediate loss of unlinked file contents

Our lab application supports SIGHUP:

kill -HUP "$PID"
sleep 2
ls -l "$LAB_DIR/logs"
lsof -nP -a -p "$PID" -d "$FD"

app.log reappears in the directory tree. The file descriptor now points to the new file, shedding the (deleted) label. Because no active processes hold the original inode open, the kernel frees its allocated disk blocks.

When working with production services, never assume SIGHUP defaults to reopening log handles. While NGINX, Apache, and standard UNIX daemons often use signals like USR1 or HUP for log reopening or configuration reloads, other runtimes may terminate immediately upon receiving them. Always consult the vendor documentation. If no native reopen interface exists, coordinating a rolling restart via sudo systemctl restart <service> and monitoring health checks provides a predictable, safer resolution path.

Emergency mitigation: When a service cannot be restarted immediately and partition exhaustion is imminent, you can truncate the underlying inode directly through its descriptor link in /proc. The process retains the open descriptor and continues writing to it from offset 0, but historical logs within that unlinked file are permanently destroyed. Only invoke this when data loss is an acceptable trade-off to prevent host-wide cascading failure.

# EMERGENCY — irreversibly destroys deleted file content. Verify PID/FD prior to execution.
: > "/proc/$PID/fd/$FD"

Truncation provides immediate triage, not a permanent fix. You must resolve the log rotation pipeline to prevent recurrence.

5. Prevention: Automated Rotation with logrotate and postrotate

The incident was triggered by manually unlinking a log file without notifying the process holding the descriptor. A standard logrotate workflow performs the same lifecycle safely: it moves (renames) the file, creates a new one (create), and executes a postrotate script to signal the application to close the old descriptor and open the new file path.[5]

Generate a lab-specific configuration. Notice the unquoted heredoc allows the shell to expand $LAB_DIR locally, while \$(...) is escaped so it evaluates when logrotate runs:

cat > "$LAB_DIR/logrotate.conf" <<EOF
$LAB_DIR/logs/app.log {
    size 5M
    rotate 3
    compress
    delaycompress
    missingok
    notifempty
    create 0640
    postrotate
        kill -HUP "\$(cat $LAB_DIR/app.pid)"
    endscript
}
EOF
cat "$LAB_DIR/logrotate.conf"

Configuration breakdown: rotate once the file exceeds 5 MB, retain 3 historical archives, compress starting from the second rotation (delaycompress ensures the most recent archive remains uncompressed and readable), and ignore missing or empty files.

Allow approximately 10 seconds for the writer to cross the 5 MB mark. Then run a dry-run in debug mode: logrotate will print its execution plan without modifying files. The -s flag isolates state tracking to an ephemeral file, leaving system-wide state untouched:

logrotate -d -s "$LAB_DIR/logrotate.state" "$LAB_DIR/logrotate.conf"
logrotate -v -s "$LAB_DIR/logrotate.state" "$LAB_DIR/logrotate.conf"
sleep 2
ls -l "$LAB_DIR/logs"
lsof -nP -a -p "$PID" -d "$FD"
grep -c 'reopened log' "$LAB_DIR/logs/app.log"

Expected result: app.log.1 (the rotated segment) exists alongside a newly allocated app.log with 0640 permissions. The process's descriptor points to the new file, which contains the string reopened log. If the descriptor still targets app.log.1, the application failed to cycle its file handle—typically caused by a malformed postrotate hook. In that failure state, the rotated file will continue to expand indefinitely despite the filename change.

For services incapable of log reopening, logrotate provides copytruncate: it copies the active log file to an archive target and truncates the original file in place. However, the logrotate documentation explicitly notes that a race condition exists between copying and truncation, creating a window where incoming logs can be lost.[5] Treat copytruncate as a fallback mechanism, not a design default.

For production services, place rotation policies in /etc/logrotate.d/<app>, referencing the exact process signal or CLI reopen command (e.g., systemctl kill -s HUP <service>). Always validate the config using sudo logrotate -d /etc/logrotate.d/<app>. If storage depletion is driven by the systemd journal, inspect allocation via journalctl --disk-usage. Note that journalctl --vacuum-size= only purges archived journal files; enforcing durable retention requires setting SystemMaxUse= within journald.conf.[6]

6. Troubleshooting Edge Cases

  • lsof +L1 returns no entries, yet du remains much lower than df: Re-run with sudo. Unprivileged users cannot query file descriptors owned by other UIDs. Next, inspect mount points for obscured data hidden underneath mounts, or check for ext4 reserved block overhead (typically 5% reserved for root).
  • The descriptor retains the (deleted) state after SIGHUP: The target binary does not implement reopen semantics on that signal. Stop testing on production and schedule a graceful restart.
  • logrotate -d outputs "log does not need rotating": The file has not yet crossed the size threshold, or the state file recorded a recent rotation run. In this lab, delete logrotate.state and re-run.
  • Disk is reported full, but df -i shows 100% inode utilization: You are experiencing inode exhaustion rather than block storage depletion. Shift your triage toward locating directories containing millions of micro-files instead of scanning for large files.

7. Teardown

Terminate the mock writer by sending Ctrl+C in the first terminal or via SIGTERM, verify the process has halted, and clean up the lab directory:

kill "$PID"
sleep 1
ps -p "$PID" >/dev/null && echo "vẫn chạy" || echo "đã dừng"
rm -r -- "$HOME/disk-lab"

This lab installed no packages, modified no files in /etc, and provisioned no cloud infrastructure, incurring zero ongoing operational overhead.

Conclusion

A discrepancy between df and du is not a tool malfunction; they inspect distinct abstraction layers within the kernel. During an incident, establish situational awareness using read-only diagnostics (df, df -i, du -x, lsof +L1), remediate by directing the application to gracefully cycle its file descriptors, and only truncate via /proc as an emergency measure where data loss is acceptable. Permanently eliminate the root cause by deploying robust logrotate configurations verified with logrotate -d. For practicing safe storage lifecycle management without data loss risk, consult the guide on Docker Compose with Healthchecks and Volumes.

References

Verified on October 22, 2026:

[1] https://man7.org/linux/man-pages/man2/unlink.2.html — unlink(2), Linux man-pages
[2] https://www.gnu.org/software/coreutils/manual/html_node/du-invocation.html — GNU coreutils, du
[3] https://man7.org/linux/man-pages/man8/lsof.8.html — lsof(8), +L1 option
[4] https://man7.org/linux/man-pages/man5/proc_pid_fd.5.html — proc_pid_fd(5)
[5] https://man7.org/linux/man-pages/man8/logrotate.8.html — logrotate(8), create/postrotate/copytruncate
[6] https://www.freedesktop.org/software/systemd/man/latest/journalctl.html — journalctl, --disk-usage/--vacuum-size

Read critically, test before applying. Examples reflect Vibe DevOps lab environments; adjust parameters to your infrastructure and verify in staging first.← Back to Hands-on Labs

Next Recommended Labs