.\" -*- coding: UTF-8 -*- .\" Copyright (C) 2013, Heinrich Schuchardt .\" .\" %%%LICENSE_START(VERBATIM) .\" Permission is granted to make and distribute verbatim copies of this .\" manual provided the copyright notice and this permission notice are .\" preserved on all copies. .\" .\" Permission is granted to copy and distribute modified versions of .\" this manual under the conditions for verbatim copying, provided that .\" the entire resulting derived work is distributed under the terms of .\" a permission notice identical to this one. .\" .\" Since the Linux kernel and libraries are constantly changing, this .\" manual page may be incorrect or out-of-date. The author(s) assume. .\" no responsibility for errors or omissions, or for damages resulting. .\" from the use of the information contained herein. The author(s) may. .\" not have taken the same level of care in the production of this. .\" manual, which is licensed free of charge, as they might when working. .\" professionally. .\" .\" Formatted or processed versions of this manual, if unaccompanied by .\" the source, must acknowledge the copyright and authors of this work. .\" %%%LICENSE_END .\"******************************************************************* .\" .\" This file was generated with po4a. Translate the source file. .\" .\"******************************************************************* .TH FANOTIFY_INIT 2 "1 ноября 2020 г." Linux "Руководство программиста Linux" .SH ИМЯ fanotify_init \- создаёт и инициализирует группу fanotify .SH СИНТАКСИС \fB#include \fP .br \fB#include \fP .PP \fBint fanotify_init(unsigned int \fP\fIflags\fP\fB, unsigned int \fP\fIevent_f_flags\fP\fB);\fP .SH ОПИСАНИЕ Обзор программного интерфейса fanotify смотрите в \fBfanotify\fP(7). .PP Вызов \fBfanotify_init\fP() инициализирует новую группу fanotify и возвращает файловый дескриптор очереди событий, связанной с группой. .PP В файловом дескрипторе, используемом в \fBfanotify_mark\fP(2), задаются файлы, каталоги, точки монтирования и файловые системы, для которых должны создаваться события fanotify. Эти события можно получить с помощью чтения файлового дескриптора. Одни события носят уведомительный характер, показывая что к файлу был получен доступ. Другие события можно использовать для разрешения приложению доступа к файлу или каталогу. Доступ к объектам файловой системы разрешается посредством записи в файловый дескриптор. .PP Несколько программ могут использовать интерфейс fanotify к одним и тем же файлам одновременно. .PP В текущей реализации количество групп fanotify ограничено 128 на пользователя. Это значение нельзя изменить. .PP Для вызова \fBfanotify_init\fP() требуется мандат \fBCAP_SYS_ADMIN\fP. Это требование может быть облегчено в будущих версиях программного интерфейса. Поэтому ниже показаны определённые дополнительные проверки возможностей, которые были реализованы. .PP Аргумент \fIflags\fP содержит многобитовое поле, определяющее класс уведомления, запрашиваемый приложением, а также однобитовые поля, задающие поведение файлового дескриптора. .PP Если на события доступа зарегистрировалось несколько слушателей, то класс уведомления используется для установления порядка слушателей при получении событий. .PP В \fIflags\fP может быть указан только один из следующих классов уведомления: .TP \fBFAN_CLASS_PRE_CONTENT\fP Это значение позволяет принимать уведомляющие события об обращении к файлу, и события доступа, запрашивающие доступ к файлу. Он предназначен для слушателей событий, которым требуется доступ к файлам до того, как в них будут содержаться окончательные данные. Этот класс уведомления может быть использован, например, в программах управления иерархического хранения. .TP \fBFAN_CLASS_CONTENT\fP Это значение позволяет принимать уведомляющие события об обращении к файлу, и события доступа, запрашивающие доступ к файлу. Он предназначен для слушателей событий, которым требуется доступ к файлам после того, как они содержат окончательные данные. Этот класс уведомления может быть использован, например, в программах обнаружения вредоносного кода. .TP \fBFAN_CLASS_NOTIF\fP Значение по умолчанию. Его не нужно указывать. Это значение позволяет принимать только события о доступе к файлу. Право на доступ к файлу задать невозможно. .PP Слушатели с различными классами уведомлений будут принимать события в таком порядке: \fBFAN_CLASS_PRE_CONTENT\fP, \fBFAN_CLASS_CONTENT\fP, \fBFAN_CLASS_NOTIF\fP. Порядок уведомления слушателей в этом классе уведомления не определён. .PP Дополнительно в \fIflags\fP могут быть установлены следующие биты: .TP \fBFAN_CLOEXEC\fP Устанавливать флаг close\-on\-exec (\fBFD_CLOEXEC\fP) для нового файлового дескриптора. Смотрите описание флага \fBO_CLOEXEC\fP в \fBopen\fP(2). .TP \fBFAN_NONBLOCK\fP Включить неблокирующий флаг (\fBO_NONBLOCK\fP) для файлового дескриптора. Чтение из такого файлового дескриптора не вызовет блокирования. Если данные отсутствуют, то \fBread\fP(2) завершается ошибкой \fBEAGAIN\fP. .TP \fBFAN_UNLIMITED_QUEUE\fP Снять ограничение в 16384 события в очереди событий. Для использования этого флага требуется мандат \fBCAP_SYS_ADMIN\fP. .TP \fBFAN_UNLIMITED_MARKS\fP Снять ограничение в 8192 метки. Для использования этого флага требуется мандат \fBCAP_SYS_ADMIN\fP. .TP \fBFAN_REPORT_TID\fP (начиная с Linux 4.20) .\" commit d0a6a87e40da49cfc7954c491d3065a25a641b29 Хранить ID нити (TID) вместо ID процесса (PID) в поле \fIpid\fP структуры \fIstruct fanotify_event_metadata\fP, передаваемой в \fBread\fP(2) (смотрите \fBfanotify\fP(7)). .TP \fBFAN_REPORT_FID\fP (начиная с Linux 5.1) .\" commit a8b13aa20afb69161b5123b4f1acc7ea0a03d360 This value allows the receipt of events which contain additional information about the underlying filesystem object correlated to an event. An additional record of type \fBFAN_EVENT_INFO_TYPE_FID\fP encapsulates the information about the object and is included alongside the generic event metadata structure. The file descriptor that is used to represent the object correlated to an event is instead substituted with a file handle. It is intended for applications that may find the use of a file handle to identify an object more suitable than a file descriptor. Additionally, it may be used for applications monitoring a directory or a filesystem that are interested in the directory entry modification events \fBFAN_CREATE\fP, \fBFAN_DELETE\fP, and \fBFAN_MOVE\fP, or in events such as \fBFAN_ATTRIB\fP, \fBFAN_DELETE_SELF\fP, and \fBFAN_MOVE_SELF\fP. All the events above require an fanotify group that identifies filesystem objects by file handles. Note that for the directory entry modification events the reported file handle identifies the modified directory and not the created/deleted/moved child object. The use of \fBFAN_CLASS_CONTENT\fP or \fBFAN_CLASS_PRE_CONTENT\fP is not permitted with this flag and will result in the error \fBEINVAL\fP. See \fBfanotify\fP(7) for additional details. .TP \fBFAN_REPORT_DIR_FID\fP (начиная с Linux 5.9) Events for fanotify groups initialized with this flag will contain (see exceptions below) additional information about a directory object correlated to an event. An additional record of type \fBFAN_EVENT_INFO_TYPE_DFID\fP encapsulates the information about the directory object and is included alongside the generic event metadata structure. For events that occur on a non\-directory object, the additional structure includes a file handle that identifies the parent directory filesystem object. Note that there is no guarantee that the directory filesystem object will be found at the location described by the file handle information at the time the event is received. When combined with the flag \fBFAN_REPORT_FID\fP, two records may be reported with events that occur on a non\-directory object, one to identify the non\-directory object itself and one to identify the parent directory object. Note that in some cases, a filesystem object does not have a parent, for example, when an event occurs on an unlinked but open file. In that case, with the \fBFAN_REPORT_FID\fP flag, the event will be reported with only one record to identify the non\-directory object itself, because there is no directory associated with the event. Without the \fBFAN_REPORT_FID\fP flag, no event will be reported. See \fBfanotify\fP(7) for additional details. .TP \fBFAN_REPORT_NAME\fP (начиная с Linux 5.9) Events for fanotify groups initialized with this flag will contain additional information about the name of the directory entry correlated to an event. This flag must be provided in conjunction with the flag \fBFAN_REPORT_DIR_FID\fP. Providing this flag value without \fBFAN_REPORT_DIR_FID\fP will result in the error \fBEINVAL\fP. This flag may be combined with the flag \fBFAN_REPORT_FID\fP. An additional record of type \fBFAN_EVENT_INFO_TYPE_DFID_NAME\fP, which encapsulates the information about the directory entry, is included alongside the generic event metadata structure and substitutes the additional information record of type \fBFAN_EVENT_INFO_TYPE_DFID\fP. The additional record includes a file handle that identifies a directory filesystem object followed by a name that identifies an entry in that directory. For the directory entry modification events \fBFAN_CREATE\fP, \fBFAN_DELETE\fP, and \fBFAN_MOVE\fP, the reported name is that of the created/deleted/moved directory entry. For other events that occur on a directory object, the reported file handle is that of the directory object itself and the reported name is '.'. For other events that occur on a non\-directory object, the reported file handle is that of the parent directory object and the reported name is the name of a directory entry where the object was located at the time of the event. The rationale behind this logic is that the reported directory file handle can be passed to \fBopen_by_handle_at\fP(2) to get an open directory file descriptor and that file descriptor along with the reported name can be used to call \fBfstatat\fP(2). The same rule that applies to record type \fBFAN_EVENT_INFO_TYPE_DFID\fP also applies to record type \fBFAN_EVENT_INFO_TYPE_DFID_NAME\fP: if a non\-directory object has no parent, either the event will not be reported or it will be reported without the directory entry information. Note that there is no guarantee that the filesystem object will be found at the location described by the directory entry information at the time the event is received. See \fBfanotify\fP(7) for additional details. .TP \fBFAN_REPORT_DFID_NAME\fP This is a synonym for (\fBFAN_REPORT_DIR_FID\fP|\fBFAN_REPORT_NAME\fP). .PP В аргументе \fIevent_f_flags\fP задаются флаги состояния файла, которые будут установлены на открытые файловые описатели, создаваемые для событий fanotify. Подробней об этих флагах смотрите описание значений \fIflags\fP в \fBopen\fP(2). Аргумент \fIevent_f_flags\fP включает многобитовое поле для режима доступа. Это поел может иметь следующие значения: .TP \fBO_RDONLY\fP Это значение разрешает доступ только на чтение. .TP \fBO_WRONLY\fP Это значение разрешает доступ только на запись. .TP \fBO_RDWR\fP Это значение разрешает доступ на чтение и запись. .PP В \fIevent_f_flags\fP могут быть установлены дополнительные биты. Наиболее полезные значения: .TP \fBO_LARGEFILE\fP Включить поддержку файлов более 2\ ГБ. Если не удастся установить этот флаг, то при попытке открыть большой файл, отслеживаемый группой fanotify на 32\-битной системе, возвращается ошибка \fBEOVERFLOW\fP. .TP \fBO_CLOEXEC\fP (начиная с Linux 3.18) .\" commit 0b37e097a648aa71d4db1ad108001e95b69a2da4 Включить флаг close\-on\-exec для нового открытого файлового дескриптора. Смотрите описание флага \fBO_CLOEXEC\fP в \fBopen\fP(2) для того, чтобы узнать как это может пригодиться. .PP Также доступны следующие флаги: \fBO_APPEND\fP, \fBO_DSYNC\fP, \fBO_NOATIME\fP, \fBO_NONBLOCK\fP и \fBO_SYNC\fP. Указание любых других флагов в \fIevent_f_flags\fPприводит к ошибке \fBEINVAL\fP (но смотрите ДЕФЕКТЫ). .SH "ВОЗВРАЩАЕМОЕ ЗНАЧЕНИЕ" При успешном выполнении \fBfanotify_init\fP() возвращает новый файловый дескриптор. При ошибке возвращается \-1, и \fIerrno\fP устанавливается в соответствующее значение. .SH ОШИБКИ .TP \fBEINVAL\fP .\" commit 23c9deeb3285d34fd243abb3d6b9f07db60c3cf4 В \fIflags\fP или \fIevent_f_flags\fP указано некорректное значение. Значение \fBFAN_ALL_INIT_FLAGS\fP (устарело, начиная с версии ядра Linux 4.20) определяет все допустимые биты в \fIflags\fP. .TP \fBEMFILE\fP Количество групп fanotify для этого пользователя превышает 128. .TP \fBEMFILE\fP Было достигнуто ограничение по количеству открытых файловых дескрипторов на процесс. .TP \fBENOMEM\fP Не удалось выделить память для группы уведомления. .TP \fBENOSYS\fP В этом ядре не реализован \fBfanotify_init\fP(). Программный интерфейс fanotify доступен только, если ядро было собрано с параметром \fBCONFIG_FANOTIFY\fP. .TP \fBEPERM\fP Операция запрещена, так как вызывающий не имеет мандата \fBCAP_SYS_ADMIN\fP. .SH ВЕРСИИ Вызов \fBfanotify_init\fP() появился в версии 2.6.36 ядра Linux и был включён в версии 2.6.37. .SH "СООТВЕТСТВИЕ СТАНДАРТАМ" Данный вызов есть только в Linux. .SH ДЕФЕКТЫ В ядрах Linux до версии 3.18 существовали следующие дефекты: .IP * 3 .\" Fixed by commit 0b37e097a648aa71d4db1ad108001e95b69a2da4 При передаче в \fIevent_f_flags\fP флаг \fBO_CLOEXEC\fP игнорируется. .PP В ядрах Linux до версии 3.14 существовали следующие дефекты: .IP * 3 .\" Fixed by commit 48149e9d3a7e924010a0daab30a6197b7d7b6580 Значение аргумента \fIevent_f_flags\fP не проверяется на корректность флагов. Могут быть установлены флаги, предназначенные только для внутреннего использования, такие как \fBFMODE_EXEC\fP, и в результате будут установлены для файловых дескрипторов при чтении из файлового дескриптора fanotify. .SH "СМ. ТАКЖЕ" \fBfanotify_mark\fP(2), \fBfanotify\fP(7) .SH ЗАМЕЧАНИЯ Эта страница является частью проекта Linux \fIman\-pages\fP версии 5.10. Описание проекта, информацию об ошибках и последнюю версию этой страницы можно найти по адресу \%https://www.kernel.org/doc/man\-pages/. .PP .SH ПЕРЕВОД Русский перевод этой страницы руководства был сделан Azamat Hackimov , Dmitry Bolkhovskikh , Yuri Kozlov и Иван Павлов . .PP Этот перевод является бесплатной документацией; прочитайте .UR https://www.gnu.org/licenses/gpl-3.0.html Стандартную общественную лицензию GNU версии 3 .UE или более позднюю, чтобы узнать об условиях авторского права. Мы не несем НИКАКОЙ ОТВЕТСТВЕННОСТИ. .PP Если вы обнаружите ошибки в переводе этой страницы руководства, пожалуйста, отправьте электронное письмо на .MT man-pages-ru-talks@lists.sourceforge.net .ME .