Linux Tips guides, explanations and reader checklists on whilenetworking.com

Mastering the ‘lsof’ Command to Find Which Process is Holding a Locked File

File locking issues are among the most frustrating obstacles in Linux system administration. When an application crashes unexpectedly, leaves a database…

File locking issues are among the most frustrating obstacles in Linux system administration. When an application crashes unexpectedly, leaves a database transaction incomplete, or a user forgets to close a file before running a backup script, the operating system may prevent other processes from accessing that resource. This results in “Permission denied” errors or hangs that can stall critical workflows. While tools like fuser exist, the lsof (List Open Files) command remains the industry standard for detailed diagnostics because it treats every open file descriptor as a distinct file, regardless of whether it is a regular text file, a socket, or a memory-mapped region.

Understanding how to interpret lsof output is essential for IT students and junior engineers who need to troubleshoot production environments quickly. This guide provides a concrete, safe lab scenario to help you master the command, explains the specific flags required for different situations, and offers verification steps to ensure system stability after resolving file locks.

Understanding the lsof Output Structure

Before attempting to resolve a lock, you must understand what the command returns. By default, lsof lists all open files on the system, which can be overwhelming. The output is organized into four main columns that are critical for diagnosis: COMMAND, PID, USER, and FD (File Descriptor).

  • COMMAND: The name of the executable running the process (e.g., mysqld, python3, vim).
  • PID: The Process ID. This is the unique identifier used to kill the process if necessary.
  • USER: The owner of the process. This helps determine if a lock is caused by a specific user’s application.
  • FD: Indicates how the process is accessing the file (e.g., u for regular open files, w for write access, cwd for current working directory).

Scenario: Resolving a Stuck Database Write Operation

Imagine you are managing a web server where the Apache service fails to write new logs because the log rotation script reports “Device or resource busy.” A junior engineer suggests restarting Apache blindly, which is risky as it might drop active connections. Instead, you decide to use lsof to identify exactly what is holding the /var/log/apache2/error.log file open.

Step 1: Locate the Locked File

First, ensure you have the exact path to the problematic file. In this scenario, we are investigating /var/log/apache2/error.log. You can run lsof with the -f flag to find files based on their inode or name, but it is often more direct to filter by the specific filename:

sudo lsof /var/log/apache2/error.log

Note: The -n flag tells lsof to show numeric network addresses instead of resolving hostnames, speeding up the lookup. The -i flag can be used for network sockets, but is not needed here.

Step 2: Analyze the Results

Suppose the output looks like this:

COMMAND   PID   USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
httpd    1234 apache 10u  REG  253,1 102400    12 /var/log/apache2/error.log

In this illustrative output:
* The COMMAND is httpd (Apache).
* The PID is 1234.
* The TYPE is REG (Regular file).
* The FD is 10u, indicating an open file descriptor with write (w) access implied if the process is writing to it.

If you see a process holding the file, that process is preventing other tools (like tail -f or log rotation) from accessing it exclusively.

Strategies for Unlocking Files Safely

Once identified, simply killing the process might not be the best first step, especially if it is a critical database server like MySQL or PostgreSQL. These systems often have internal mechanisms to handle locks or require a specific restart sequence.

Option A: Graceful Restart

If the holding process is Apache (httpd) and it is stuck writing logs, the safest approach is often to rotate the log file using logrotate with force options, which handles the open descriptor gracefully on modern systems. Alternatively, if the process is hung but not crashing, try sending a signal to make it close the file:

sudo kill -SIGTERM 1234

Wait a few seconds and check if the file is now accessible:

ls -l /var/log/apache2/error.log

Option B: Investigating Database Locks

If the locked file belongs to a database (e.g., an SQL dump file), killing the database process directly can lead to data corruption. In this case, you must check the application logs for errors and potentially use the database’s built-in command to drop locks or perform a checkpoint. For example, in MySQL, you might query the information_schema.innodb_locks table to see which transaction holds the lock.

Option C: The Nuclear Option (Last Resort)

If the process is truly zombie-like and unresponsive, and you have verified that no active data is being written at that exact moment, you may need to terminate the process forcefully. Warning: Always verify with the ps command first to ensure you are targeting the correct PID.

sudo kill -9 1234

Verification and Common Errors

After taking action, verification is crucial. A common error occurs when users assume a file is unlocked immediately after killing a process. However, in some cases (like NFS mounts or specific socket types), the kernel may take a moment to release the inode.

Common Mistake: Running lsof without sudo.
The lsof command requires elevated privileges to read file descriptor information of other processes. If you run it as a standard user, you will likely get a “Permission denied” error even if files are open. Always prepend sudo.

Common Mistake: Ignoring the FD type.
Sometimes a file appears locked but is actually just being accessed by a process that has read-only access. If your goal is to overwrite the file, a read-only lock might not be an issue; however, if the process expects exclusive write access, it will fail. Check the ACCESS column in verbose lsof output (using -a) to see if permissions are RW (Read/Write) or R-- (Read only).

Student Practice Task: Simulating a Lock

To solidify your skills, try this exercise in a virtual machine or local lab environment:
1. Open two separate terminal windows.
2. In the first window, open a file with a text editor like nano: sudo nano /tmp/testfile.txt.
3. In the second window, try to append data to the same file using echo "data" >> /tmp/testfile.txt.
4. You will likely receive an error or find the command hangs depending on your filesystem settings and editor locking behavior.
5. Run sudo lsof /tmp/testfile.txt in the second window (or a third) to identify the PID of the nano process.
6. Close the file in the first window using Ctrl+X, then verify with lsof again that no processes are holding it.

Industry Application: Automating Lock Checks

In production environments, administrators often integrate lsof into monitoring scripts. For instance, a systemd unit or a cron job can periodically run a check to see if the main application log is locked by a runaway process. If lsof returns a PID, the script can alert the operations team via Slack or email rather than waiting for a crash.

# Example one-liner to check if /var/log/syslog is locked
if sudo lsof /var/log/syslog | grep -q "syslogd"; then
    echo "WARNING: Syslog is locked by PID $(sudo lsof /var/log/syslog | awk '{print $2}')" | wall
fi

Conclusion

Mastering lsof transforms file locking from a mysterious error into a solvable diagnostic puzzle. By understanding the output columns, respecting process ownership, and choosing between graceful restarts and forceful termination based on the application type, you can maintain system stability without risking data integrity. Remember that terms, availability, and specific behaviors depend heavily on your Linux distribution version and kernel configuration. Always verify your changes in a test environment before applying them to critical production servers.

Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.