Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Understanding lsof (List Open Files)
3.
Syntax of lsof Command
4.
Options Available in lsof Command
4.1.
-u User
4.2.
-p Process ID
4.3.
-i Internet
4.4.
+D Directory
4.5.
-d File Descriptor
4.6.
-n and -N
4.7.
-l
5.
Practical Example of How to List Open Files in Linux
5.1.
How to List All Open Files on the System
5.2.
How to Show Files Opened by a Particular User
5.3.
How to List All Files Which Are Opened by Everyone Except a Specific User
5.4.
How to List All Open Files by a Particular Process
5.5.
How to List All Open Files That Are Opened by a Particular Process ID
5.6.
Files Opened by All Other PID
5.7.
How to List Parent Process IDs
5.8.
How to List All Opened Files Opened by a Directory
5.9.
How to Open Files by Network Connections
6.
Frequently Asked Questions
6.1.
Can lsof show files opened by deleted or zombie processes?
6.2.
How can lsof help in identifying security issues?
6.3.
Is lsof capable of closing open files?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Lsof Command in Linux

Author Rinki Deka
0 upvote
Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

Introduction

Linux systems thrive on robust command-line tools that empower users to perform difficult operations with precision. Among these, the lsof command stands out for its utility in managing system resources effectively. Short for "List Open Files," this command reveals a treasure trove of information about files opened by processes running on a Linux system. 

Lsof Command in Linux

By the end of this article, you'll understand how to get the advantage the lsof command to track down open files, understand its syntax, and navigate its options. We'll explaore practical scenarios, demonstrating how to list open files across various contexts, thereby enhancing your Linux troubleshooting and monitoring skills.

Understanding lsof (List Open Files)

The lsof command in Linux is a go-to tool for system administrators and power users alike. It provides a comprehensive view of all files currently open by processes on the system. This not only includes regular data files but also directories, libraries, network connections, and devices. Understanding lsof is crucial because every operation on a Linux system involves opening, reading, writing, or closing files. By mastering this command, you can diagnose system issues, monitor resource usage, and ensure security by tracking file access.

At its core, lsof helps in identifying which processes are using which files. This can be particularly useful for solving a variety of system administration tasks, such as finding out which process is holding a particular file when you're trying to unmount a filesystem, or identifying network connections a process is making.

Let's take a simple example: Suppose you're trying to unmount a USB drive but the system keeps telling you that the device is busy. By using lsof, you can quickly identify which process is accessing files on the USB drive, allowing you to terminate the process or close the file, and successfully unmount the drive.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Syntax of lsof Command

The syntax of the lsof command is straightforward yet powerful, allowing for a wide range of queries about open files. The basic structure of the command is:

lsof [options] [names]

Here, [options] allows you to refine your search, targeting specific files, users, processes, or even network connections. The [names] field is optional and can be used to narrow down the list to specific files or directories.

For instance, running lsof without any options or names will list all open files for all active processes, which might be overwhelming due to the volume of data. To make the output more manageable, you can use options like -u to filter by username, -p to specify a process ID, or -i to focus on Internet and network connections.

Here's a quick example to illustrate the syntax in action:

lsof -u username


This command will list all files opened by processes belonging to username. It's a handy way to see what specific users are up to, which files they're accessing, and how they're interacting with the system.

Another example is:

lsof /path/to/directory


This will list all open files within a specified directory, providing insights into which processes are interacting with that directory's contents.

Options Available in lsof Command

The lsof command is equipped with a plethora of options that cater to various needs and scenarios, making it a versatile tool for system administrators. Here's a closer look at some of the most commonly used options and how they can be applied in practical situations:

-u User

This option allows filtering the list of open files by user name or user ID. For example, lsof -u sam will list all files opened by the user named Sam.

-p Process ID

To view files opened by a specific process, you can use this option followed by the process ID. For instance, lsof -p 1234 will show all files associated with the process ID 1234.

-i Internet

This powerful option filters the output to show network connections. You can specify protocol types like TCP or UDP and even port numbers, such as lsof -i TCP:22 to see all TCP connections on port 22 (SSH).

+D Directory

If you're interested in all open files within a particular directory and its subdirectories, +D comes in handy. For example, lsof +D /var/log lists open files under /var/log.

-d File Descriptor

Every open file is associated with a file descriptor, and with -d, you can filter the list by specific descriptors. For example, lsof -d 2 will list all files that are using file descriptor 2 (standard error).

-n and -N

These options prevent the conversion of network numbers to host names (-n) and port names (-N), speeding up the command and making the output more readable in certain contexts.

-l

This option forces lsof to display user IDs instead of user names, useful in environments with a lot of users.

These options can be combined to form more complex queries, offering a granular view of the system's open files. For instance, to find out which files are opened by a specific user on a specific device, you might use:

lsof -u sam -d /dev/sda1


This command lists all files that the user Sam has opened on the device /dev/sda1.

Practical Example of How to List Open Files in Linux

Let's dive into practical examples to demonstrate the versatility and power of the lsof command. These examples will cover common scenarios that you might encounter while managing or troubleshooting a Linux system.

How to List All Open Files on the System

To get an overview of all open files on your system, you can simply run lsof without any options:

lsof


This command will produce a lengthy list, showing every open file by every process running on the system. It's a broad sweep, useful for getting a high-level view but might require further filtering to find specific information.

How to Show Files Opened by a Particular User

If you're interested in what files a specific user has open, you can use the -u option. For example, to see all files opened by the user alex, you would use:

lsof -u alex


This filters the list to only show files that are opened by processes owned by alex, making it easier to monitor individual user activities.

How to List All Files Which Are Opened by Everyone Except a Specific User

To invert the search and list files opened by everyone except a specific user, you can prefix the username with a caret (^). For instance, to exclude user alex, you would run:

lsof -u ^alex


This command is useful when you want to exclude system or service accounts that might clutter the output with numerous entries.

How to List All Open Files by a Particular Process

When troubleshooting or monitoring, you might want to focus on a specific process. Using the -p option with a process ID allows you to do just that. For example, for process ID 1087:

lsof -p 1087


This will list all files that the process with ID 1087 has opened, providing insights into the resources the process is using.

How to List All Open Files That Are Opened by a Particular Process ID

This is similar to the previous example but can be expanded to include multiple process IDs by separating them with commas:

lsof -p 1087,2023,3456


This command lists open files for processes with IDs 1087, 2023, and 3456, allowing for a comparative view across multiple processes.

Files Opened by All Other PID

To list files not associated with particular PIDs, combine the -p option with the caret (^):

lsof -p ^1087


This command shows all files not opened by the process with ID 1087, useful for isolating the impact of specific processes.

How to List Parent Process IDs

To identify the parent process IDs of processes holding open files, you can use the -R option:

lsof -R


This adds a PPID (Parent Process ID) column to the output, helping to trace file usage back to parent processes.

How to List All Opened Files Opened by a Directory

To see all open files within a specific directory, use the +D option followed by the directory path:

lsof +D /home/alex


This command lists all files opened within the /home/alex directory, including those in subdirectories.

How to Open Files by Network Connections

For listing files associated with network connections, the -i option is your tool. For example, to list all TCP connections:

lsof -i TCP


This command is invaluable for monitoring network activity, identifying unwanted connections, or troubleshooting network applications.

These examples illustrate the flexibility of the lsof command in various scenarios, from simple listings to complex filters tailored to specific needs. With practice, you'll find lsof an indispensable part of your Linux toolkit.

Frequently Asked Questions

Can lsof show files opened by deleted or zombie processes?

Yes, lsof can list files that were opened by processes that have since been deleted or have become zombies. These files often appear with (deleted) appended to the file name in the lsof output.

How can lsof help in identifying security issues?

lsof can be used to spot unauthorized or unexpected network connections or files being accessed by processes, which might indicate a security breach or malware activity.

Is lsof capable of closing open files?

No, lsof is a diagnostic tool designed to list open files and does not have the capability to close them. To close an open file, you would need to terminate the process using it or use other system commands depending on the situation.

Conclusion

Mastering the lsof command equips you with the ability to peer into the workings of your Linux system, offering insights into file and network resource usage that are invaluable for system monitoring, troubleshooting, and security. From identifying what's keeping a device busy to diagnosing network issues, lsof is a versatile tool that should be in every Linux user's toolkit. The practical examples and scenarios we've explored highlight just a fraction of its potential applications. As you become more familiar with its options and nuances, you'll discover even more ways to harness the power of lsof to keep your system running smoothly and securely.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Previous article
Vim Command in Linux
Next article
Cat Command in Linux
Live masterclass