Linux show files opened by process

Linux: Show Opened Files, lsof

You can use the command lsof to list all files opened by processes.

In unix/linux, “everything” is a file. Devices (such as all USB device) are files, network sockets are files, directory is a file.

Here’s some of the commonly used options.

lsof -h Display a short help documentation. lsof fpath Show all that has opened file at fpath lsof -i List files associated with internet (For example, browser process) lsof -u userName Show all with login/uid userName lsof -p pid By pid. 123,^456 lsof +d dir By dir path dir lsof +D dir By dir path dir , also show all dir’s children lsof -c cmd Show files opened by command whose name starts with cmd lsof showing first few files opened by firefox

FD means “file descriptor”. Common FD code are:

cwd Current working directory ltx Shared library text (code and data) m86 DOS Merge mapped file mem Memory-mapped file mmap Memory-mapped device pd Parent directory rtd Root directory txt Program text (code and data) number File descriptor. 0 is stdin, 1 is stdout, 2 is stderr. A letter after it means mode. “u” = read and write. “r” = read. “w” = write.

see man lsof for complete list and description.

TYPE в†’ is the file type. Common types are:

REG Regular file LINK Symbolic link file DIR Directory BLK Block special file (device file) CHR Character special file (device file) FIFO FIFO special file PIPE Pipes PMEM /proc memory image file IPv4 IPv4 socket IPv6 Open IPv6 network file — even if its address is IPv4, mapped in an IPv6 address inet Internet domain socket sock Socket of unknown domain unix UNIX domain socket

Источник

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 $ ps -aef | grep httpd
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 OR
$ ps -C -o pid=
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/$/fd
# 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 ‘‘ | sort | uniq -c | sort -r | head
## force numeric sort by passing the ‘-n’ option to the sort ##
# lsof | awk ‘‘ | sort | uniq -c | sort -r -n | head

  • 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

Источник

Вики 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

Источник

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’.

Источник

Читайте также:  Авто тюнинг по windows
Оцените статью