- Linux / UNIX List Open Files for Process
- UNIX List Open Files For Process
- FreeBSD list open files per process
- Linux List Open Files For Process
- Using lsof to display the processes using the most file handles
- Conclusion
- Find Open Files in Linux
- Jarret W. Buse
- How to Find Files in Linux Using the Command Line
- Find a File in Linux by Name or Extension
- Using Common find Commands and Syntax to Find a File in Linux
- Basic Examples
- Options and Optimization for find
- Find a File in Linux by Modification Time
- Use grep to Find a File in Linux Based on Content
- How to Find and Process a File in Linux
- How to Find and Delete a File in Linux
- More Information
Linux / UNIX List Open Files for Process
H ow do I list all open files for a Linux or UNIX process using command line options? How can I show open files per process under Linux?
Both Linux and Unix-like operating systems come with various utilities to find out open files associated with the process.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | Yes |
Requirements | None |
Est. reading time | 3 minutes |
UNIX List Open Files For Process
First use the ps command command to get PID of process, enter:
$ ps -aef | grep
Next pass this PID to pfiles command under Solaris Unix:
$ pfiles
$ pfiles 3533
See pfiles command documentation> for more information or type the following man command:
% man pfiles
FreeBSD list open files per process
On FreeBSD use the fstat command along with the ps command:
# ps aux | grep -i openvpn # filter outputs using the grep command #
# fstat -p
# fstat -p 1219
We can count open files count for openvpn process as follows using the wc command:
# fstat -p 1219 | grep -v ^USER | wc -l
The -p option passed to the fstat to report all files open by the specified process.
FreeBSD pstat command in action
Linux List Open Files For Process
First you need to find out PID of process. Simply use any one of the following command to obtain process id:
# ps aux | grep
$ ps -C
For example, find out PID of firefox web-browser, enter:
$ ps -C firefox -o pid=
Output:
To list opne files for firefox process, enter:
$ ls -l /proc/7857/fd
Sample output:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
For privileged process use the sudo command and to count open files use the wc command on Linux as follows:
# Get process pid
sudo ps -C Xorg -o pid
sudo ls -l /proc/$
# Say pid is 9497 for Xorg, then
sudo ls -l /proc/9497/fd | wc -l
We can use bash for loop as follows too:
Listing Open Files on Linux
Using lsof to display the processes using the most file handles
The lsof command list open files under all Linux distributions or UNIX-like operating system. Type the following command to list open file for process ID 351:
$ lsof -p 351
In this example display and count all open files for top 10 processes on Linux operating systems or server:
# lsof | awk ‘
## force numeric sort by passing the ‘-n’ option to the sort ##
# lsof | awk ‘
- lsof – Run the lsof to display all open files and send output to the awk
- awk ‘
‘ – Display first field i.e. process name only - uniq -c – Omit duplicate lines while prefix lines by the number of occurrences
- sort -r – Reverse sort
- head – Display top 10 process along with open files count
Conclusion
Now you know how to find open files per process on Linux, FreeBSD, and Unix-like systems using various command-line options. See how to increase the system-wide/user-wide number of available (open) file handles on Linux for more information.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
Find Open Files in Linux
Jarret W. Buse
Guest
Find Open Files in Linux
Sometimes within any Operating System (OS), it is difficult to know when you have a file opened which needs to be managed in some way. There is nothing more stressful than trying to delete, cut or modify a file and get the error that the file is already open. Another possibility is trying to unmount a device and you get the error that the device is busy, which is usually due to an open file on the device.
So, let’s look at how to find open files because you really do not want to have to close all your open applications to get the right one.
Let’s assume I am trying to unmount sda2 and I get an error:
umount: /media/sda2: device is busy.
It is best that you do not perform a forced unmount so that files are not corrupted.
To get a list of open files on sda2, use the “lsof”’ command as shown in Figure 1.
From Figure 1, you can see there are nine columns for information about the open file:
- COMMAND – procrss which has the file open
- PID (Process ID) – the PID of the process which has the file opened
- USER – the user which has the file open
- FD (File Descriptor) – indicator used to access files
- TYPE – type of node for file
- REG – regular file
- DIR – directory
- CHR – Character special file
- FIFO – First In First Out
- IP4 – IP4 socket
- IP6 – IP6 network file
- AX25 – AX.25 socket
- INET – Internet domain socket
- LLA – HP-UX link level access file
- RTE – AF-Route socket
- SOCK – unknown domain socket
- UNIX – UNIX domain socket
- X.25 – HP-UX x.25 domain socket
- BLK – Block special file
- DEL – deleted Linux map file
- DOOR – VDOOR file
- KQUEUE – BSD kernel event queue file
- LINK – Symbolic Link (soft link) file
- MPB – Multiplexed block file
- MPC – Multiplexed character file
- NOFD – /proc/
/fd/ directory
- PAS – /proc/as/ file
- PAXV — /proc/auxv/ file
- PCRE — /proc/cred/ file
- PCTL — /proc control file
- PCUR – current /proc control file
- PCWD — /proc current working directory
- PDIR — /proc directory
- PETY — /proc executable type
- PFD — /proc file descriptor
- PFDR — /proc file descriptor directory
- PFIL — /proc executable file
- PFPR — /proc FP register set
- PGD — /proc/pagedata file
- PGID — /proc group notifier file
- PIPE — pipes
- PLC — /proc/lwpctl file
- PLDR — /proc/lpw directory
- PLDT — /proc/ldt file
- PLPI – proc/lpsinfo file
- PLST — /proc/lsstatus file
- PLU — /proc/lusage file
- PLWG — /proc/gwindows file
- PLWI — /proc/lwpsinfo file
- PLWS — /proc/lwpstatus file
- PLWU — /proc/lwpusage file
- PLWX — /proc/xregs file
- PMAP — /proc map file
- PMEM — /proc memory image file
- PNTF — /proc process notifier file
- POBJ — /proc/object file
- PODR — /proc/object directory
- POLP — /proc light weight process file
- POPF — /proc PID file
- POPG — /proc page data file
- PORT – SYSV named pipe
- PREG — /proc register file
- PRMP — /proc/rmap file
- PRTD — /proc root directory
- PSGA — /proc/sigact file
- PSIN — /proc/psinfo file
- PSTA — /proc status file
- PSXSEM – POSIX semaphore file
- PSXSHM – POSIX shared memory file
- PUSG — /proc/usage file
- PW — /proc/watch file
- PXMP — /proc/xmap file
- SMT – shared memory transport file
- STSO – stream socket
- UNM – unnamed type file
- XNAM – OpenServer Xenix special file of unknown type
- XSEM – OpenServer Xenix semaphore file
- XSD – OpenServer Xenix shared data file
As you can see from Figure 1, the command was run specifically for the ‘sda2’ partition. If the ‘lsof’ command were executed with no location specified, it would check the local filesystem and all mounted filesystems.
If you are wanting a list of all files opened by a certain process, you can use the ‘-c NAME’ parameter to specify the name of the process, or just a few letters. For example, if I wanted to see all files opened by Libre Office (the command ‘soffice.b’) on all drives I could use the following command:
lsof -c soffice.b
I could also specify a specific device, such as sda2 as follows:
lsof -c soffice.b /dev/sda2/
If your system is having issues resolving the username, you can use the parameter ‘-l’ to make it show the User ID (UID) instead of the username.
For network numbers to host name conversion, you can use the parameter ‘-n’ to prevent the conversion. This can make the ‘lsof’ command run a little faster when dealing with network issues.
For port number to port name conversion, you can use the ‘-P’ parameter to prevent the conversion.
Once you have found the program which has the open file, you should be able to easily find it and close it. At an extreme, ‘top’ can be used from the Terminal to kill the process, once you know its name. It is also possible to issue the following command to send a ‘sigterm’ signal to the process:
kill -SIGTERM `lsof -t /dev/sda2/`
NOTE: SIGTERM (15) can be ignored by some applications, but a SIGKILL (9)
cannot be ignored. Instead of the name as a parameter, the numbers
can be used.
Assume you want to kill all processes created by a user. You would do the
following:
kill -9 `lsof -t -u `
The ‘-u ‘ allows you to specify which user processes you
are searching for in the open files. The ‘-9’ is a SIGKILL
parameter.
NOTE: The special symbol (`) is sometimes called a slash quote. It is
located under the tilde (
). It is used to enclose commands which
need to be executed first. The output is sent to the outer command.
Источник
How to Find Files in Linux Using the Command Line
When you have to find a file in Linux, it’s sometimes not as easy as finding a file in another operating system. This is especially true if you are running Linux without a graphical user interface and need to rely on the command line. This article covers the basics of how to find a file in Linux using the CLI. The find command in Linux is used to find a file (or files) by recursively filtering objects in the file system based on a simple conditional mechanism. You can use the find command to search for a file or directory on your file system. By using the -exec flag ( find -exec ), files can be found and immediately processed within the same command.
Find a File in Linux by Name or Extension
Use find from the command line to locate a specific file by name or extension. The following example searches for *.err files in the /home/username/ directory and all sub-directories:
Using Common find Commands and Syntax to Find a File in Linux
find expressions take the following form:
- The options attribute will control the find process’s behavior and optimization method.
- The starting/path attribute will define the top-level directory where find begins filtering.
- The expression attribute controls the tests that search the directory hierarchy to produce output.
Consider the following example command:
This command enables the maximum optimization level (-O3) and allows find to follow symbolic links ( -L ). find searches the entire directory tree beneath /var/www/ for files that end with .html .
Basic Examples
Command | Description |
---|---|
find . -name testfile.txt | Find a file called testfile.txt in current and sub-directories. |
find /home -name *.jpg | Find all .jpg files in the /home and sub-directories. |
find . -type f -empty | Find an empty file within the current directory. |
find /home -user exampleuser -mtime -7 -iname «.db» | Find all .db files (ignoring text case) modified in the last 7 days by a user named exampleuser. |
Options and Optimization for find
The default configuration for find will ignore symbolic links (shortcut files). If you want find to follow and return symbolic links, you can add the -L option to the command, as shown in the example above.
find optimizes its filtering strategy to increase performance. Three user-selectable optimization levels are specified as -O1 , -O2 , and -O3 . The -O1 optimization is the default and forces find to filter based on filename before running all other tests.
Optimization at the -O2 level prioritizes file name filters, as in -O1 , and then runs all file-type filtering before proceeding with other more resource-intensive conditions. Level -O3 optimization allows find to perform the most severe optimization and reorders all tests based on their relative expense and the likelihood of their success.
Command | Description |
---|---|
-O1 | (Default) filter based on file name first. |
-O2 | File name first, then file type. |
-O3 | Allow find to automatically re-order the search based on efficient use of resources and likelihood of success. |
-maxdepth X | Search current directory as well as all sub-directories X levels deep. |
-iname | Search without regard for text case. |
-not | Return only results that do not match the test case. |
-type f | Search for files. |
-type d | Search for directories. |
Find a File in Linux by Modification Time
The find command contains the ability to filter a directory hierarchy based on when the file was last modified:
The first command returns a list of all files in the entire file system that end with the characters conf and modified in the last seven days. The second command filters exampleuser user’s home directory for files with names that end with the characters conf and modified in the previous three days.
Use grep to Find a File in Linux Based on Content
The find command can only filter the directory hierarchy based on a file’s name and metadata. If you need to search based on the file’s content, use a tool like grep . Consider the following example:
This searches every object in the current directory hierarchy ( . ) that is a file ( -type f ) and then runs the command grep «example» for every file that satisfies the conditions. The files that match are printed on the screen ( -print ). The curly braces ( <> ) are a placeholder for the find match results. The <> are enclosed in single quotes ( ‘ ) to avoid handing grep a malformed file name. The -exec command is terminated with a semicolon ( ; ), which should be escaped ( \; ) to avoid interpretation by the shell.
How to Find and Process a File in Linux
The -exec option runs commands against every object that matches the find expression. Consider the following example:
This filters every object in the current hierarchy ( . ) for files named rc.conf and runs the chmod o+r command to modify the find results’ file permissions.
The commands run with the -exec are executed in the find process’s root directory. Use -execdir to perform the specified command in the directory where the match resides. This may alleviate security concerns and produce a more desirable performance for some operations.
The -exec or -execdir options run without further prompts. If you prefer to be prompted before action is taken, replace -exec with -ok or -execdir with -okdir .
How to Find and Delete a File in Linux
To delete the files that end up matching your search, you can add -delete at the end of the expression. Do this only when you are positive the results will only match the files you wish to delete.
In the following example, find locates all files in the hierarchy starting at the current directory and fully recursing into the directory tree. In this example, find will delete all files that end with the characters .err :
More Information
You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.
This page was originally published on Monday, October 25, 2010.
Источник