Jump to content

прокфс

(Перенаправлено из /proc )

Файловая система proc ( procfs ) — это специальная файловая система в Unix-подобных операционных системах, которая представляет информацию о процессах и другую системную информацию в иерархической файловой структуре, обеспечивая более удобный и стандартизированный метод динамического доступа к данным процесса, хранящимся в ядре, чем традиционные методы трассировки или прямой доступ к памяти ядра . он сопоставляется с точкой монтирования с именем /proc Обычно во время загрузки . Файловая система proc действует как интерфейс для внутренних структур данных о запущенных процессах в ядре. В Linux его также можно использовать для получения информации о ядре и изменения определенных параметров ядра во время выполнения ( sysctl ).

Многие Unix-подобные операционные системы поддерживают файловую систему proc, включая System V , Solaris , IRIX , Tru64 UNIX , BSD , Linux , IBM AIX , [ 1 ] QNX и Plan 9 от Bell Labs . Поддержка OpenBSD прекращена в версии 5.7, выпущенной в мае 2015 года. Она отсутствует в HP-UX. [ 1 ] и macOS . [ 2 ]

Ядро Linux расширяет его до данных, не связанных с процессом.

Файловая система proc обеспечивает метод связи между пространством ядра и пространством пользователя . Например, версия GNU утилиты отчетов о процессах ps использует файловую систему proc для получения своих данных без использования каких-либо специализированных системных вызовов .

History

[edit]

UNIX 8th Edition

[edit]

Tom J. Killian implemented the UNIX 8th Edition (V8) version of /proc: he presented a paper titled "Processes as Files" at USENIX in June 1984. The design of procfs aimed to replace the ptrace system call used for process tracing. Detailed documentation can be found in the proc(4) manual page.

SVR3

[edit]

The original AT&T System V Release 3 (SVR3) operating system (available internally to AT&T in 1986 and generally in 1987) did not come with the /proc filesystem, but a subsequent incremental version of it did. It only contained files representing the processes rather than the now common subdirectories.

SVR4

[edit]

Roger Faulkner and Ron Gomes ported V8 /proc to SVR4, and published a paper called "The Process File System and Process Model in UNIX System V" at USENIX in January 1991. This kind of procfs supported the creation of ps, but the files could only be accessed with functions read(), write(), and ioctl(). Between 1995 and 1996, Roger Faulkner created the procfs-2 interface for Solaris-2.6 that offers a structured /proc filesystem with sub-directories.

Plan 9

[edit]

Plan 9 implemented a process file system, but went further than V8. V8's process file system implemented a single file per process. Plan 9 created a hierarchy of separate files to provide those functions, and made /proc a real part of the file system.

4.4BSD and derivatives

[edit]

4.4BSD cloned its implementation of /proc from Plan 9.[citation needed] As of February 2011, procfs is gradually becoming phased out in FreeBSD,[3] and it has turned to use the sysctl interface instead for process-related information. To provide binary compatibility with Linux user space programs, the FreeBSD kernel also provides linprocfs that is similar to the Linux procfs.[4] It was removed from OpenBSD in version 5.7, which was released in May 2015, because it "always suffered from race conditions and is now unused".[5] macOS did not implement procfs and user space programs have to use the sysctl interface for retrieving process data.[2]

Solaris

[edit]

/proc in Solaris was available from the beginning (June 1992). Solaris 2.6 in 1996 introduced procfs2 from Roger Faulkner.

Linux

[edit]

Linux first added a /proc filesystem in v0.97.3, September 1992, and first began expanding it to non-process related data in v0.98.6, December 1992.

As of 2020, the Linux implementation includes a directory for each running process, including kernel processes, in directories named /proc/PID, where PID is the process number. Each directory contains information about one process, including:

  • /proc/PID/cmdline, the command that originally started the process.
  • /proc/PID/cwd, a symlink to the current working directory of the process.
  • /proc/PID/environ contains the names and values of the environment variables that affect the process.
  • /proc/PID/exe, a symlink to the original executable file, if it still exists (a process may continue running after its original executable has been deleted or replaced).
  • /proc/PID/fd, a directory containing a symbolic link for each open file descriptor.
  • /proc/PID/fdinfo, a directory containing entries which describe the position and flags for each open file descriptor.
  • /proc/PID/maps, a text file containing information about mapped files and blocks (like heap and stack).
  • /proc/PID/mem, a binary image representing the process's virtual memory, can only be accessed by a ptrace'ing process.
  • /proc/PID/root, a symlink to the root path as seen by the process. For most processes this will be a link to / unless the process is running in a chroot jail.
  • /proc/PID/status contains basic information about a process including its run state and memory usage.
  • /proc/PID/task, a directory containing hard links to any tasks that have been started by this (i.e.: the parent) process.

(Users may obtain the PID with a utility such as pgrep, pidof or ps:

$ ls -l /proc/$(pgrep -n python3)/fd        # List all file descriptors of the most recently started `python3' process
total 0
lrwx------ 1 baldur baldur 64 2020-03-18 12:31 0 -> /dev/pts/3
lrwx------ 1 baldur baldur 64 2020-03-18 12:31 1 -> /dev/pts/3
lrwx------ 1 baldur baldur 64 2020-03-18 12:31 2 -> /dev/pts/3
$ readlink /proc/$(pgrep -n python3)/exe    # List executable used to launch the most recently started `python3' process  
/usr/bin/python3.8

)

/proc also includes non-process-related system information, although in the 2.6 kernel much of that information moved to a separate pseudo-file system, sysfs, mounted under /sys:

  • depending on the mode of power management (if at all), either directory, /proc/acpi or /proc/apm, which predate sysfs and contain various bits of information about the state of power management.
  • /proc/buddyinfo, information about the buddy algorithm that handles memory fragmentation.[6]
  • /proc/bus, containing directories representing various buses on the computer, such as PCI/USB. This has been largely superseded by sysfs under /sys/bus which is far more informative.
  • /proc/fb, a list of the available framebuffers
  • /proc/cmdline, giving the boot options passed to the kernel
  • /proc/cpuinfo, containing information about the CPU, such as its vendor (and CPU family, model and model names which should allow users to identify the CPU) and its speed (CPU clockspeed), cache size, number of siblings, cores, and CPU flags. The format and available information is highly architecture-depended. On some architectures, /proc/cpuinfo includes a value for "bogomips", frequently misconstrued as a measure of CPU speed, like a benchmark, but it does not actually measure any sensible (for end-users) value at all. It occurs as a side-effect of kernel timer calibration and yields highly varying values depending on CPU type, even at equal clock speeds.
$ cat /proc/cpuinfo
processor   : 0
 vendor_id  : AuthenticAMD
 cpu family : 16
 model      : 6
 model name : AMD Athlon(tm) II X2 270 Processor
 stepping   : 3
 microcode  : 0x10000c8
 cpu MHz    : 2000.000
 cache size : 1024 KB
 ...
 processor  : 1
 vendor_id  : AuthenticAMD
 cpu family : 16
 model      : 6
 model name : AMD Athlon(tm) II X2 270 Processor
 stepping   : 3
 microcode  : 0x10000c8
 cpu MHz    : 800.000
 cache size : 1024 KB
 ...

On multi-core CPUs, /proc/cpuinfo contains the fields for "siblings" and "cpu cores" which represent the following calculation is applied:[7]

"siblings" = (HT per CPU package) * (# of cores per CPU package)
"cpu cores" = (# of cores per CPU package)

A CPU package means physical CPU which can have multiple cores (single core for one, dual core for two, quad core for four). This allows a distinction between hyper-threading and dual-core, i.e. the number of hyper-threads per CPU package can be calculated by siblings / CPU cores. If both values for a CPU package are the same, then hyper-threading is not supported.[8] For instance, a CPU package with siblings=2 and "cpu cores"=2 is a dual-core CPU but does not support hyper-threading.

  • /proc/crypto, a list of available cryptographic modules
  • /proc/devices, a list of character and block devices sorted by device ID but giving the major part of the /dev name too
  • /proc/diskstats, giving some information (including device numbers) for each of the logical disk devices
  • /proc/filesystems, a list of the file systems supported by the kernel at the time of listing
  • /proc/interrupts, /proc/iomem, /proc/ioports and the directory /proc/irq, giving some details about the devices (physical or logical) using the various system resources
  • /proc/kmsg, holding messages output by the kernel[9]
  • /proc/loadavg, containing stats about the current load average in the last minutes.
  • /proc/meminfo, containing a summary of how the kernel is managing its memory.
  • /proc/modules, one of the most important files in /proc, containing a list of the kernel modules currently loaded . It gives some indication (not always entirely correct) of dependencies.
  • /proc/mounts, a symlink to self/mounts which contains a list of the currently mounted devices and their mount points (and which file system is in use and what mount options are in use).
  • /proc/net/, a directory containing useful information about the network stack, in particular /proc/net/nf_conntrack, which lists existing network connections (particularly useful for tracking routing when iptables FORWARD is used to redirect network connections)
  • /proc/partitions, a list of the device-numbers, their size and /dev names which the kernel has identified as existing partitions
  • /proc/scsi, giving information about any devices connected via a SCSI or RAID controller
  • a symbolic link to the current (traversing) process at /proc/self (i.e. /proc/PID/ where PID is that of the current process).
  • /proc/slabinfo , список статистики кэшей для часто используемых объектов в ядре Linux.
  • /proc/swaps — список активных разделов подкачки, их различные размеры и приоритеты.
  • Доступ к динамически настраиваемым параметрам ядра в разделе /прок/система . Под В /proc/sys появляются каталоги, представляющие области ядра, содержащие виртуальные файлы, доступные для чтения и записи .
    Например, часто упоминаемый виртуальный файл: /proc/sys/net/ipv4/ip_forward , поскольку он необходим для маршрутизации межсетевых экранов или туннелей. Файл содержит либо «1», либо «0»: если он равен 1, стек IPv4 пересылает пакеты, не предназначенные для локального хоста, если он равен 0, то нет.
  • /proc/sysvipc о совместном использовании памяти и межпроцессном взаимодействии (IPC). , содержащий информацию
  • /proc/tty , содержащий информацию о текущих терминалах; /proc/tty/driver выглядит так [ оригинальное исследование? ] список различных типов доступных tty , каждый из которых представляет собой список устройств каждого типа
  • /proc/uptime — время, в течение которого ядро ​​работало с момента загрузки и находилось в режиме ожидания (оба в секундах)
  • /proc/version , содержащий версию ядра Linux, номер дистрибутива, номер версии gcc (используемый для сборки ядра) и любую другую соответствующую информацию, относящуюся к версии ядра, работающей в данный момент.
  • другие файлы в зависимости от различного оборудования, конфигураций модулей и изменений в ядре.

Основные утилиты, использующие /proc в Linux, входят в состав procps ( /procprocesses ) и функционируют только в сочетании с смонтированным /проц .

Cygwin реализовал procfs, который по сути такой же, как procfs в Linux.

  1. ^ Перейти обратно: а б Немет, Эви; Снайдер, Гарт; Хейн, Трент Р.; Уэйли, Бен (14 июля 2010 г.). Руководство по системному администрированию UNIX и Linux . Пирсон Образование. п. 136. ИСБН  978-0-13-211736-4 .
  2. ^ Перейти обратно: а б Амит Сингх (2003). «/proc в Mac OS X» . Внутреннее устройство Mac OS X: Книга . Архивировано из оригинала 4 мая 2012 года . Проверено 10 июля 2021 г.
  3. ^ «Почему procfs устарел в пользу procstat?» . freebsd.org . 22 февраля 2011 г.
  4. ^ "linprocfs(5)" . Страницы руководства FreeBSD . Проект FreeBSD. 13 ноября 2019 года . Проверено 12 июня 2021 г.
  5. ^ «Подробные изменения между OpenBSD 5.6 и 5.7» . openbsd.org .
  6. ^ «3.2.2. /proc/buddyinfo» . centos.org . Архивировано из оригинала 2 сентября 2013 года . Проверено 23 мая 2011 г.
  7. ^ Барон, Джейсон. «HT против двухъядерности» . Архивировано из оригинала 13 мая 2016 года . Проверено 28 июня 2011 г.
  8. ^ «Понимание Linux /proc/cpuinfo» . richweb.com . Архивировано из оригинала 3 апреля 2012 года . Проверено 21 апреля 2015 г.
  9. ^ Нгуен, Бинь (30 июля 2004 г.). «Иерархия файловой системы Linux» . Бинь Нгуен. п. 63 . Проверено 18 июля 2016 г. /proc/kmsg[:] Сообщения, выводимые ядром. Они также направляются в системный журнал.

Источники

[ редактировать ]
[ редактировать ]
Arc.Ask3.Ru: конец переведенного документа.
Arc.Ask3.Ru
Номер скриншота №: 1dd219aa20f6b5a704e21bf01146e330__1708364160
URL1:https://arc.ask3.ru/arc/aa/1d/30/1dd219aa20f6b5a704e21bf01146e330.html
Заголовок, (Title) документа по адресу, URL1:
procfs - Wikipedia
Данный printscreen веб страницы (снимок веб страницы, скриншот веб страницы), визуально-программная копия документа расположенного по адресу URL1 и сохраненная в файл, имеет: квалифицированную, усовершенствованную (подтверждены: метки времени, валидность сертификата), открепленную ЭЦП (приложена к данному файлу), что может быть использовано для подтверждения содержания и факта существования документа в этот момент времени. Права на данный скриншот принадлежат администрации Ask3.ru, использование в качестве доказательства только с письменного разрешения правообладателя скриншота. Администрация Ask3.ru не несет ответственности за информацию размещенную на данном скриншоте. Права на прочие зарегистрированные элементы любого права, изображенные на снимках принадлежат их владельцам. Качество перевода предоставляется как есть. Любые претензии, иски не могут быть предъявлены. Если вы не согласны с любым пунктом перечисленным выше, вы не можете использовать данный сайт и информация размещенную на нем (сайте/странице), немедленно покиньте данный сайт. В случае нарушения любого пункта перечисленного выше, штраф 55! (Пятьдесят пять факториал, Денежную единицу (имеющую самостоятельную стоимость) можете выбрать самостоятельно, выплаичвается товарами в течение 7 дней с момента нарушения.)