Find open deleted files and verify disk space reclamation

Find open deleted files and verify disk space reclamation

Find open deleted files and verify disk space reclamation

You delete a large export file. It is no longer in the directory, yet df shows almost no increase in available space. Deleting more directories at this point could cause further data loss without addressing the cause: a process still has the deleted file open. The goal is to establish the relationship between the filesystem, inode, process, and file handle, then close the references and verify that space is reclaimed—not start by rebooting the entire dedicated server.

1. Identify the filesystem behind the discrepancy

The following steps assume Debian 12 with a local ext4 or XFS filesystem. You need administrator privileges and lsof and python3 installed. For an AmdSrv server, retrieve the credentials from the control panel after payment and connect over SSH; if multiple addresses are listed, use the first one. This article does not cover formatting or changes to storage arrays.

Start with the path your application actually uses:

findmnt -T /var/tmp
df -B1 /var/tmp
sudo du -x -B1 -s /var/tmp

df reports block usage across the entire filesystem, whereas du reports the space used by files in the directory tree it can traverse. You therefore cannot directly subtract the result for /var/tmp from the total for the root filesystem. To compare the two, run du -x against the mount point returned by findmnt, and retain any permission error messages. Scanning large directories also generates metadata read load.

A discrepancy is only a clue. Filesystem metadata, reserved blocks, snapshots, and files hidden beneath mount points can all affect the results. Record the mount source, filesystem type, and sampling time first. Keep subsequent comparisons within the same filesystem so that changes on different disks do not get mixed together.

2. Trace open handles by device number and inode

List files that have a link count of less than one but are still open:

sudo lsof -nP +L1

Focus on COMMAND, PID, FD, DEVICE, SIZE/OFF, NLINK, and NODE. Regular files usually appear as REG, and their names may include (deleted). Multiple processes or file descriptors can reference the same file, so do not add up space usage by output row.

Verify the handle, not just the name

Set the following variables to the process ID and numeric file descriptor recorded during your investigation. For example, 7w in lsof corresponds to file descriptor 7; do not copy the trailing access-mode marker.

pid=12345
fd=7
sudo readlink "/proc/$pid/fd/$fd"
sudo stat -Lc 'dev=%d inode=%i links=%h size=%s blocks=%b unit=%B' \
  "/proc/$pid/fd/$fd"
sudo ps -p "$pid" -o pid,ppid,user,lstart,args
sudo systemctl status "$pid" --no-pager

These numbers only demonstrate how to set the variables; replace them before running the commands. blocks × unit is closer to the file's allocated disk usage than its logical size. A sparse file can have a large logical size while using very little space. Deduplicate by the device-number-and-inode pair, since different filesystems can contain the same inode number.

systemctl status can help identify the owning unit, but not every process belongs to a separate service. Be careful when collecting command lines: they may contain sensitive parameters. Redact those details before including them in support tickets or shared records.

Do not truncate an unfamiliar file through /proc/PID/fd/FD. A deleted pathname does not mean the contents are no longer in use. Databases, temporary sorting operations, and archiving jobs may still depend on that data.

3. Reproduce the release conditions in a separate directory

Before starting, make sure the filesystem containing /var/tmp has enough free space. This experiment writes approximately 32 MiB of actual data rather than creating a sparse file. Run it entirely within the same Bash session. The background Python process writes the data, removes the directory entry, and keeps the handle open for observation.

case_dir=$(mktemp -d /var/tmp/open-unlinked.XXXXXX)
df -B1 "$case_dir"

python3 - "$case_dir" <<'PY' &
import os
import signal
import sys
from pathlib import Path

base = Path(sys.argv[1])
path = base / "payload.bin"
with path.open("wb") as stream:
    for _ in range(32):
        stream.write(b"x" * (1024 * 1024))
    stream.flush()
    os.fsync(stream.fileno())
    path.unlink()
    (base / "ready").touch()
    signal.pause()
PY
demo_pid=$!

for attempt in $(seq 1 50); do
  test -e "$case_dir/ready" && break
  kill -0 "$demo_pid" 2>/dev/null || break
  sleep 0.1
done

test -e "$case_dir/ready"
sudo lsof -nP -a -p "$demo_pid" +L1
du -B1 -s "$case_dir"
df -B1 "$case_dir"

Interpret the results only if test succeeds. Otherwise, check the background process for errors first. You should find no payload.bin in the directory, very little usage reported by du, and a matching deleted file in lsof. Other processes may be writing to the filesystem at the same time, so the change in df does not have to match the test file's size exactly.

Once you have finished observing, terminate only the test process started in this session:

kill -TERM "$demo_pid"
wait "$demo_pid" || true
df -B1 "$case_dir"
rm -f -- "$case_dir/ready"
rmdir -- "$case_dir"

A nonzero return from wait is expected when the process terminates because of a signal. After the handle closes, you should see available space increase. Do not apply this method of terminating the test process directly to production processes, and do not replace the targeted deletion here with recursive cleanup.

4. Let service behavior determine safe production actions

Once you have identified the process holding the file open, establish what the file is used for. An export job might be waiting to upload it, an application might depend on an anonymous temporary file, or an old log might not have been reopened after rotation. Follow this order: establish the file's purpose, pause related changes, preserve evidence, and then choose an operation supported by the service.

If the service documentation explicitly provides a command or signal to reopen output files, follow those instructions. Do not assume that all services respond to the same signal. A normal configuration reload does not necessarily close an old file either. Verify that the handle disappears rather than treating a successful command exit as proof of completion.

If there is no reopen mechanism, arrange a controlled restart, first addressing request draining, task checkpoints, and write consistency. For database files, follow the database's own recovery procedures rather than forcibly modifying files through their descriptors.

Closing the last file descriptor does not always remove the last reference: a memory mapping may still retain one. If a file is held only by a mapping, there may no longer be a corresponding path in /proc/PID/fd, so you also need to inspect the process's memory mappings. If usage does not fall after the service restarts, look again for other processes holding references instead of repeatedly restarting the service.

5. Verify reclamation with three sets of evidence

Validation must cover references, capacity, and application behavior. First, rerun lsof +L1 and confirm that the target device-number-and-inode pair is no longer held open. Second, check df -B1 again at the same mount point. Third, check the service status and complete actual read and write requests. Confirming that the process is running again does not prove that the data-processing chain is working.

Keep before-and-after records of the inode, process start time, allocated block count, and application validation results. PIDs can be reused, so always recheck the process identity during follow-up. If the handle has disappeared but the capacity change is not apparent, investigate snapshots, concurrent writes, or filesystem space accounting. Do not keep acting on an object that has already been closed.

For routine monitoring, look for regular files with a zero link count that still have substantial block allocations. Deduplicate by device number and inode, and use growth trends when setting alerts. Completion does not mean the directory looks cleaner: it means the target references have been released, available space can be accounted for, and application reads and writes have passed validation.

Frequently asked questions

Why does a deleted file still occupy disk space?

Unlinking removes a directory entry, but an open handle can keep the file referenced. On an ordinary local filesystem, its blocks become eligible for reclamation after the last reference closes; snapshots may retain those blocks longer.

Is truncating /proc/PID/fd/FD a safe fix?

Not as a general procedure. It changes a file that a running process still uses and can corrupt application data or state. Identify the owning service and file purpose, then use a supported file-reopen operation or a controlled restart.

AmdSrv Dedicated Server with AMD EPYC 7543P, from $458/month

From deployment notes to configuration checks

Choose a server based on memory, storage, and network requirements. The customer manages the operating system and data backups.