- 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
- How to Find Out Who is Using a File in Linux
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- Вики IT-KB
- Инструменты пользователя
- Инструменты сайта
- Боковая панель
- Содержание
- Как проверить все открытые файлы пользователем или процессом в Linux
- Лимит ядра Linux
- Методика подсчёта открытых файлов
- Примеры получения данных
- How to use the Linux ‘lsof’ command to list open files
- lsof command background
- I assume you’re logged in as root
- Basic Linux lsof command examples
- Common lsof options
- Summary: Linux lsof command examples
- 15 Linux lsof Command Examples (Identify Open Files)
- 1. Introduction to lsof
- 2. List processes which opened a specific file
- 3. List opened files under a directory
- 4. List opened files based on process names starting with
- 5. List processes using a mount point
- 6. List files opened by a specific user
- 7. List all open files by a specific process
- 8. Kill all process that belongs to a particular user
- 9. Combine more list options using OR/AND
- 10. Execute lsof in repeat mode
- Finding Network Connection
- 11. List all network connections
- 12. List all network files in use by a specific process
- 13. List processes which are listening on a particular port
- 14. List all TCP or UDP connections
- 15. List all Network File System ( NFS ) files
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
Источник
How to Find Out Who is Using a File in Linux
In this article, we will explain how to find out who is using a particular file in Linux. This will help you know the system user or process that is using an open file.
We can use the lsof command to know if someone is using a file, and if they are, who. It reads kernel memory in its search for open files and helps you list all open files. In this case, an open file may be a regular file, a directory, a block special file, a character special file, a stream, a network file and many others – because in Linux everything is a file.
Lsof is used on a file system to identify who is using any files on that file system. You can run lsof command on Linux filesystem and the output identifies the owner and process information for processes using the file as shown in the following output.
To list user specific opened files, run the following command replace tecmint with the actual user name.
Another important use of lsof is to find out the process listening on a specific port. For example identify the process listening on port 80 using the following command.
Note: Since lsof reads kernel memory in its search for open files, rapid changes in kernel memory may result into unpredictable outputs. This is one of the major downsides of using lsof command.
For more information, look at the lsof man page:
That’s all! In this article, we have explained how to know who is using a particular file in Linux. We have shown how to identify the owner and process information for processes using an open file. Use the feedback form below to reach us for any questions or comments.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник
Вики IT-KB
Пошаговые руководства, шпаргалки, полезные ссылки.
Инструменты пользователя
Инструменты сайта
Боковая панель
Содержание
Как проверить все открытые файлы пользователем или процессом в Linux
В некоторых ситуациях на Linux могут возникать ошибки, связанные с превышением лимита использования файловых дескрипторов. Эти лимиты накладываются как самим ядром Linux, так и его программными модулями, например PAM.
Лимит ядра Linux
Узнать текущее значение максимального количества файловых дескрипторов, определяемое ядром Linux можно командой:
Этот лимит может быть изменён без перезагрузки системы (начинает действовать сразу и действует до перезагрузки):
Чтобы требуемое значение использовалось постоянно, то есть действовало и после перезагрузки, его необходимо определить в конфиг.файле /etc/sysclt.conf :
Методика подсчёта открытых файлов
Для получения информации о количестве всех открытых файлов всеми процессами в Linux некоторые «знатоки» предлагают использовать команду типа
Однако такая команда показывает гораздо большее значение, чем всего открыто файлов в системе на данный момент на самом деле. Это связано с тем, что по несколько раз в подсчёт попадают одни и теже открытые файлы, используемые разными процессами.
Поэтому проще для получения общего числа открытых файлов использовать данные ядра Linux
Первое число — общее количество занятых/используемых на данный момент времени файловых дескрипторов.
Второе число — количество выделенных процессам, но не используемых в данный момент дескрипторов.
Третье число — максимальное количество открытых дескрипторов
Примеры получения данных
Получить список TOP-20 процессов с самым большим количеством открытых файловых дескрипторов:
Подсчитать количество открытых файлов в разрезе процессов (в первой колонке будет выведен PID процесса, во второй количество открытых файлов этим процессом):
Посмотреть открытые файловые дескрипторы во всех процессах для отдельно взятого пользователя, например «apache»
Подсчитать количество открытых файлов в каждом процессе для отдельно взятого пользователя:
Тоже самое, только в реальном режиме времени:
Посмотреть открыте файловые дескриптры для отдельно взятого процесса (по PID процесса):
Подсчитать количество файловых дескриптров для отдельно взятого процесса:
Дополнительные источники информации:
Проверено на следующих конфигурациях:
Версия ОС |
---|
Debian GNU/Linux 8.10 (jessie) |
Автор первичной редакции:
Алексей Максимов
Время публикации: 09.06.2018 11:18
Источник
How to use the Linux ‘lsof’ command to list open files
Linux “open files” FAQ: Can you share some examples of how to show open files on a Linux system (i.e., how to use the lsof command)?
lsof command background
The Linux lsof command lists information about files that are open by processes running on the system. The lsof command is an acronym for, “list of open files.” In this article I’ll share some lsof command examples.
I assume you’re logged in as root
One other note: In these examples I’ll assume that you’re logged in as the Unix/Linux root user. If not, you’re lsof command output may be significantly limited. If you’re logged in as a non-root user, either su to root, or use sudo to run these commands.
Basic Linux lsof command examples
Typing the lsof command by itself lists all open files belonging to all active processes on the system:
On my current macOS system, which has been running for a long time, this shows a lot of open files, 1,582 to be specific:
Note that I didn’t have to be logged in as the root user to see this information on my Mac system.
Adding the head command to lsof shows what some of this output looks like:
Common lsof options
As mentioned, these details go on for 1,582 lines, so it helps to have some way to weed through that output, whether that involves using the grep command, or some of the lsof options shown below.
This command lists all open files belonging to PID (process ID) 11925 :
This command lists all open files belonging to processes owned by the user named «al»:
This command lists files that are open in the directory specified, but it does not descend into sub-directories:
The next command lists files that are open in the directory specified, and also descends into sub-directories. Beware: this can take a very long time to run for large directory structures:
Summary: Linux lsof command examples
I hope these Linux lsof command examples have been helpful. As you can see, the lsof command can be used to generate a list of open files on your Unix and Linux system with a variety of different command line options for different circumstances.
For more information on the lsof command, please see the «Related» block on this page, follow this link to lsof command search results on this website, or leave a note in the Comments section below.
Источник
15 Linux lsof Command Examples (Identify Open Files)
lsof stands for List Open Files.
It is easy to remember lsof command if you think of it as “ls + of”, where ls stands for list, and of stands for open files.
It is a command line utility which is used to list the information about the files that are opened by various processes. In unix, everything is a file, ( pipes, sockets, directories, devices, etc.). So by using lsof, you can get the information about any opened files.
1. Introduction to lsof
Simply typing lsof will provide a list of all open files belonging to all active processes.
By default One file per line is displayed. Most of the columns are self explanatory. We will explain the details about couple of cryptic columns (FD and TYPE).
FD – Represents the file descriptor. Some of the values of FDs are,
- cwd – Current Working Directory
- txt – Text file
- mem – Memory mapped file
- mmap – Memory mapped device
- NUMBER – Represent the actual file descriptor. The character after the number i.e ‘1u’, represents the mode in which the file is opened. r for read, w for write, u for read and write.
TYPE – Specifies the type of the file. Some of the values of TYPEs are,
- REG – Regular File
- DIR – Directory
- FIFO – First In First Out
- CHR – Character special file
For a complete list of FD & TYPE, refer man lsof.
2. List processes which opened a specific file
You can list only the processes which opened a specific file, by providing the filename as arguments.
3. List opened files under a directory
You can list the processes which opened files under a specified directory using ‘+D’ option. +D will recurse the sub directories also. If you don’t want lsof to recurse, then use ‘+d’ option.
4. List opened files based on process names starting with
You can list the files opened by process names starting with a string, using ‘-c’ option. -c followed by the process name will list the files opened by the process starting with that processes name. You can give multiple -c switch on a single command line.
5. List processes using a mount point
Sometime when we try to umount a directory, the system will say “Device or Resource Busy” error. So we need to find out what are all the processes using the mount point and kill those processes to umount the directory. By using lsof we can find those processes.
The following will also work.
6. List files opened by a specific user
In order to find the list of files opened by a specific users, use ‘-u’ option.
Sometimes you may want to list files opened by all users, expect some 1 or 2. In that case you can use the ‘^’ to exclude only the particular user as follows
The above command listed all the files opened by all users, expect user ‘lakshmanan’.
7. List all open files by a specific process
You can list all the files opened by a specific process using ‘-p’ option. It will be helpful sometimes to get more information about a specific process.
8. Kill all process that belongs to a particular user
When you want to kill all the processes which has files opened by a specific user, you can use ‘-t’ option to list output only the process id of the process, and pass it to kill as follows
The above command will kill all process belonging to user ‘lakshmanan’, which has files opened.
Similarly you can also use ‘-t’ in many ways. For example, to list process id of a process which opened /var/log/syslog can be done by
Talking about kill, did you know that there are 4 Ways to Kill a Process?
9. Combine more list options using OR/AND
By default when you use more than one list option in lsof, they will be ORed. For example,
The above command uses two list options, ‘-u’ and ‘-c’. So the command will list process belongs to user ‘lakshmanan’ as well as process name starts with ‘init’.
But when you want to list a process belongs to user ‘lakshmanan’ and the process name starts with ‘init’, you can use ‘-a’ option.
The above command will not output anything, because there is no such process named ‘init’ belonging to user ‘lakshmanan’.
10. Execute lsof in repeat mode
lsof also support Repeat mode. It will first list files based on the given parameters, and delay for specified seconds and again list files based on the given parameters. It can be interrupted by a signal.
Repeat mode can be enabled by using ‘-r’ or ‘+r’. If ‘+r’ is used then, the repeat mode will end when no open files are found. ‘-r’ will continue to list,delay,list until a interrupt is given irrespective of files are opened or not.
Each cycle output will be separated by using ‘=======’. You also also specify the time delay as ‘-r’ | ‘+r’.
In the above output, for the first 5 seconds, there is no output. After that a script named “inita.sh” is started, and it list the output.
Finding Network Connection
Network connections are also files. So we can find information about them by using lsof.
11. List all network connections
You can list all the network connections opened by using ‘-i’ option.
You can also use ‘-i4’ or ‘-i6’ to list only ‘IPV4’ or ‘IPV6‘ respectively.
12. List all network files in use by a specific process
You can list all the network files which is being used by a process as follows
You can also use the following
The above command will list the network files opened by the processes starting with ssh.
13. List processes which are listening on a particular port
You can list the processes which are listening on a particular port by using ‘-i’ with ‘:’ as follows
14. List all TCP or UDP connections
You can list all the TCP or UDP connections by specifying the protocol using ‘-i’.
15. List all Network File System ( NFS ) files
You can list all the NFS files by using ‘-N’ option. The following lsof command will list all NFS files used by user ‘lakshmanan’.
Источник