- Работа с процессами в Linux
- Список процессов
- Ключи
- Примеры
- Убить процесс
- Подробная информация о процессе
- Потребление ресурсов процессами
- Overview
- /proc/stat
- /proc//status
- Threads
- VmPeak
- VmSize
- VmLck
- VmHWM
- VmRSS
- VmData, VmStk, VmExe
- VmLib
- VmPTE
- /proc//stat
- 1. pid %d
- 2. comm %s
- 3. state %c
- 4. ppid %d
- 5. pgrp %d
- 6. session %d
- 7. tty_nr %d
- 8. tpgid %d
- 9. flags %u (%lu before Linux 2.6.22)
- 10. minflt %lu
- 11. cminflt %lu
- 12. majflt %lu
- 13. cmajflt %lu
- 14. utime %lu
- 15. stime %lu
- 16. cutime %ld
- 17. cstime %ld
- 18. priority %ld
- 19. nice %ld
- 20. num_threads %ld
- 21. itrealvalue %ld
- 22. starttime %llu (was %lu before Linux 2.6)
- 23. vsize %lu
- 24. rss %ld
- 25. rsslim %lu
- 26. startcode %lu
- 27. endcode %lu
- 28. startstack %lu
- 29. kstkesp %lu
- 30. kstkeip %lu
- 31. signal %lu
- 32. blocked %lu
- 33. sigignore %lu
- 34. sigcatch %lu
- 35. wchan %lu
- 36. nswap %lu
- 37. cnswap %lu
- 38. exit_signal %d (since Linux 2.1.22)
- 39. processor %d (since Linux 2.2.8)
- 40. rt_priority %u (since Linux 2.5.19; was %lu before Linux 2.6.22)
- 41. policy %u (since Linux 2.5.19; was %lu before Linux 2.6.22)
- 42. delayacct_blkio_ticks %llu (since Linux 2.6.18)
- 43. guest_time %lu (since Linux 2.6.24)
- 44. cguest_time %ld (since Linux 2.6.24)
Работа с процессами в Linux
Обновлено: 29.03.2023 Опубликовано: 09.11.2017
Список процессов
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 661 0.0 0.0 4072 8 tty1 Ss+ Jul03 0:00 /sbin/mingetty
root 662 0.0 0.0 4072 8 tty2 Ss+ Jul03 0:00 /sbin/mingetty
root 16355 0.0 0.0 171636 3308 pts/0 S 15:46 0:00 sudo su
root 16366 0.0 0.0 140896 1556 pts/0 S 15:46 0:00 su
root 16368 0.0 0.0 108316 1944 pts/0 S 15:46 0:00 bash
root 18830 0.0 0.0 110244 1172 pts/0 R+ 16:20 0:00 ps u
- USER — учетная запись пользователя, от которой запущен процесс.
- PID — идентификатор процесса.
- %CPU — потребление процессорного времени в процентном эквиваленте.
- %MEM — использование памяти в процентах.
- VSZ — Virtual Set Size. Виртуальный размер процесса (в килобайтах).
- RSS — Resident Set Size. Размер резидентного набора (количество 1K-страниц в памяти).
- TTY — терминал, из под которого был запущен процесс.
- STAT — текущее состояние процесса. Могут принимать значения:
- R — выполнимый процесс;
- S — спящий;
- D — в состоянии подкачки на диске;
- T — остановлен;
- Z — зомби.
- W — не имеет резидентных страниц;
- < —высоко-приоритетный;
- N — низко-приоритетный;
- L — имеет страницы, заблокированные в памяти.
- START — дата запуска процесса.
- TIME — время запуска процесса.
- COMMAND — команда, запустившая процесс.
Ключи
Ключ | Описание |
---|---|
-A | Все процессы. |
-a | Запущенные в текущем терминале, кроме главных системных. |
-d | Все, кроме главных системных процессов сеанса. |
-e | Все процессы. |
f | Показать дерево процессов с родителями. |
T | Все на конкретном терминале. |
a | Все, связанные с текущим терминалом и терминалами других пользователей. |
r | Список только работающих процессов. |
x | Отсоединённые от терминала. |
u | Показать пользователей, запустивших процесс. |
Примеры
Поиск процесса с помощью grep:
Убить процесс
Останавливаем процесс по его PID:
Если процесс не завершается, убиваем его принудительно:
Остановить все процессы с именем nginx:
Как и в случае с kill, можно это сделать принудительно:
Можно остановить все процессы конкретного пользователя:
Ищем процесс по имени, извлекаем его PID и завершаем его:
kill `ps aux | grep ‘apache’ | awk »`
* обратите внимание, что запрос может вывести несколько процессов, которые будут попадать под критерии поиска — в таком случае, они будут завершены все.
Подробная информация о процессе
Для каждого процесса создается каталог по пути /proc/ , в котором создаются папки и файлы с описанием процесса.
Примеры использования /proc/
Адрес в ячейках оперативной памяти, которые занял процесс:
Команда, которой был запущен процесс:
Символьная ссылка на рабочий каталог процесса:
Символьная ссылка на исполняемый файл, запустивший процесс:
Увидеть ссылки на дескрипторы открытых файлов, которые затрагивает процесс:
Подробное описание на сайте man7.org.
Потребление ресурсов процессами
Для просмотра статистики потребления ресурсов используем утилиту top:
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
21059 root 20 0 157884 2280 1496 R 18,8 0,1 0:00.03 top
1 root 20 0 190996 2964 1652 S 0,0 0,1 6:49.99 systemd
2 root 20 0 0 0 0 S 0,0 0,0 0:01.78 kthreadd
3 root 20 0 0 0 0 S 0,0 0,0 0:24.75 ksoftirqd/0
5 root 0 -20 0 0 0 S 0,0 0,0 0:00.00 kworker/0:0H
- PID — идентификатор процесса.
- USER — имя учетной записи, от которой запущен процесс.
- PR — приоритет процесса.
- NI — приоритет, выставленной командой nice.
- VIRT — объем виртуальной памяти, потребляемый процессом.
- RES — объем используемой оперативной памяти.
- SHR — количество разделяемой памяти, которое используется процессом.
- S — состояние процесса.
- %CPU — процент использования процессорного времени.
- %MEM — потребление оперативной памяти в процентах.
- TIME — использование процессорного времени в секундах.
- COMMAND — команда, которая запустила процесс.
Overview
Consolidated information about all processes running on the system can be found in /proc/stat.
Information about an individual process can be found in /proc//.
For system-level and user-level limits, see:
/proc/stat
This file contains consolidated information about all processes running on the system: counters for the total number of processes in the system, the number of running processes, number of blocked processes, etc.
cat /proc/stat cpu 39570 0 . cpu0 10155 0 . cpu1 10019 0 . cpu2 9738 0 1. cpu3 9656 0 . intr 2896032 82 . ctxt 4297127 btime 1492812098 processes 8713 procs_running 1 procs_blocked 0 softirq 1172895 0 .
/proc/
/proc//status
Contains synthetic information about the process:
Threads
Number of threads in process containing this thread.
This is a script that reports the number of threads for a Java process:
VmPeak
VmSize
VmLck
VmHWM
Peak resident set size («high water mark»).
VmRSS
VmData, VmStk, VmExe
Size of data, stack, and text segments.
VmLib
VmPTE
Page table entries size (since Linux 2.6.10).
/proc//stat
More details about the type of information found there can be obtained with man proc.
Contains status information about the process, on a single line. It is defined in /usr/src/linux/fs/proc/array.c.
Fields, in order, with their proper scanf(3) format specifiers:
1. pid %d
2. comm %s
The filename of the executable, in parentheses. This is visible whether or not the executable is swapped out.
3. state %c
One character from the string «RSDZTW» where R is running, S is sleeping in an interruptible wait, D is waiting in uninterruptible disk sleep, Z is zombie, T is traced or stopped (on a signal), and W is paging.
4. ppid %d
5. pgrp %d
The process group ID of the process.
6. session %d
The session ID of the process.
7. tty_nr %d
The controlling terminal of the process. (The minor device number is contained in the combination of bits 31 to 20 and 7 to 0; the major device number is in bits 15 t0 8.)
8. tpgid %d
The ID of the foreground process group of the controlling terminal of the process.
9. flags %u (%lu before Linux 2.6.22)
The kernel flags word of the process. For bit meanings, see the PF_* defines in . Details depend on the kernel version.
10. minflt %lu
The number of minor faults the process has made which have not required loading a memory page from disk.
11. cminflt %lu
The number of minor faults that the process’s waited-for children have made.
12. majflt %lu
The number of major faults the process has made which have required loading a memory page from disk.
13. cmajflt %lu
The number of major faults that the process’s waited-for children have made.
14. utime %lu
Amount of time that this process has been scheduled in user mode, measured in clock ticks (divide by sysconf(_SC_CLK_TCK). This includes guest time, guest_time (time spent running a virtual CPU, see below), so that applications that are not aware of the guest time field do not lose that time from their calculations.
15. stime %lu
Amount of time that this process has been scheduled in kernel mode, measured in clock ticks (divide by sysconf(_SC_CLK_TCK).
16. cutime %ld
Amount of time that this process’s waited-for children have been scheduled in user mode, measured in clock ticks (divide by sysconf(_SC_CLK_TCK). (See also times(2).) This includes guest time, cguest_time (time spent running a virtual CPU, see below).
17. cstime %ld
Amount of time that this process’s waited-for children have been scheduled in kernel mode, measured in clock ticks (divide by sysconf(_SC_CLK_TCK).
18. priority %ld
(Explanation for Linux 2.6) For processes running a real-time scheduling policy (policy below; see sched_setscheduler(2)), this is the negated scheduling priority, minus one; that is, a number in the range -2 to -100, corresponding to real-time priorities 1 to 99. For processes running under a non-real-time scheduling policy, this is the raw nice value (setpriority(2)) as represented in the kernel. The kernel stores nice values as numbers in the range 0 (high) to 39 (low), corresponding to the user-visible nice range of -20 to 19. Before Linux 2.6, this was a scaled value based on the scheduler weighting given to this process.
19. nice %ld
The nice value (see setpriority(2)), a value in the range 19 (low priority) to -20 (high priority).
20. num_threads %ld
Number of threads in this process (since Linux 2.6). Before kernel 2.6, this field was hard coded to 0 as a placeholder for an earlier removed field.
21. itrealvalue %ld
The time in jiffies before the next SIGALRM is sent to the process due to an interval timer. Since kernel 2.6.17, this field is no longer maintained, and is hard coded as 0.
22. starttime %llu (was %lu before Linux 2.6)
The time in jiffies the process started after system boot.
23. vsize %lu
Virtual memory size in bytes.
24. rss %ld
Resident Set Size: number of pages the process has in real memory. This is just the pages which count towards text, data, or stack space. This does not include pages which have not been demand-loaded in, or which are swapped out.
25. rsslim %lu
Current soft limit in bytes on the rss of the process; see the description of RLIMIT_RSS in getpriority(2).
26. startcode %lu
The address above which program text can run.
27. endcode %lu
The address below which program text can run.
28. startstack %lu
The address of the start (i.e., bottom) of the stack.
29. kstkesp %lu
The current value of ESP (stack pointer), as found in the kernel stack page for the process.
30. kstkeip %lu
The current EIP (instruction pointer).
31. signal %lu
The bitmap of pending signals, displayed as a decimal number. Obsolete, because it does not provide information on real-time signals; use /proc/[pid]/status instead.
32. blocked %lu
The bitmap of blocked signals, displayed as a decimal number. Obsolete, because it does not provide information on real-time signals; use /proc/[pid]/status instead.
33. sigignore %lu
The bitmap of ignored signals, displayed as a decimal number. Obsolete, because it does not provide information on real-time signals; use /proc/[pid]/status instead.
34. sigcatch %lu
The bitmap of caught signals, displayed as a decimal number. Obsolete, because it does not provide information on real-time signals; use /proc/[pid]/status instead.
35. wchan %lu
This is the «channel» in which the process is waiting. It is the address of a system call, and can be looked up in a namelist if you need a textual name. (If you have an up-to-date /etc/psdatabase, then try ps -l to see the WCHAN field in action.)
36. nswap %lu
Number of pages swapped (not maintained).
37. cnswap %lu
Cumulative nswap for child processes (not maintained).
38. exit_signal %d (since Linux 2.1.22)
Signal to be sent to parent when we die.
39. processor %d (since Linux 2.2.8)
CPU number last executed on.
40. rt_priority %u (since Linux 2.5.19; was %lu before Linux 2.6.22)
Real-time scheduling priority, a number in the range 1 to 99 for processes scheduled under a real-time policy, or 0, for non-real-time processes (see sched_setscheduler(2)).
41. policy %u (since Linux 2.5.19; was %lu before Linux 2.6.22)
Scheduling policy (see sched_setscheduler(2)). Decode using the SCHED_* constants in linux/sched.h.
42. delayacct_blkio_ticks %llu (since Linux 2.6.18)
Aggregated block I/O delays, measured in clock ticks (centiseconds).
43. guest_time %lu (since Linux 2.6.24)
Guest time of the process (time spent running a virtual CPU for a guest operating system), measured in clock ticks (divide by sysconf(_SC_CLK_TCK).
44. cguest_time %ld (since Linux 2.6.24)
Guest time of the process’s children, measured in clock ticks (divide by sysconf(_SC_CLK_TCK).