.\" -*- coding: UTF-8 -*- .\" Copyright (c) 2020 Stephen Kitt .\" and Copyright (c) 2021 Michael Kerrisk .\" .\" SPDX-License-Identifier: Linux-man-pages-copyleft .\" .\"******************************************************************* .\" .\" This file was generated with po4a. Translate the source file. .\" .\"******************************************************************* .TH close_range 2 "15 июня 2024 г." "Справочные страницы Linux 6.9.1" .SH НАИМЕНОВАНИЕ close_range \- закрыть все файловые дескрипторы в указанном диапазоне .SH БИБЛИОТЕКА Стандартная библиотека языка C (\fIlibc\fP, \fI\-lc\fP) .SH ОБЗОР .nf \fB#define _GNU_SOURCE\fP /* см. feature_test_macros(7) */ \fB#include \fP .P \fB#include \fP /* Definition of \fBCLOSE_RANGE_*\fP constants */ .P \fBint close_range(unsigned int \fP\fIfirst\fP\fB, unsigned int \fP\fIlast\fP\fB, int \fP\fIflags\fP\fB);\fP .fi .SH ОПИСАНИЕ Системный вызов \fBclose_range\fP() закрывает все открытые файловые дескрипторы от \fIfirst\fP до \fIlast\fP (включительно). .P Ошибки закрытия указанного файлового дескриптора в настоящее время игнорируются. .P \fIflags\fP \- это битовая маска, содержащая 0 или более из следующих: .TP \fBCLOSE_RANGE_CLOEXEC\fP (начиная с Linux 5.11) Установить флаг close\-on\-exec для указанных файловых дескрипторов, вместо того, чтобы немедленно их закрыть. .TP \fBCLOSE_RANGE_UNSHARE\fP Unshare the specified file descriptors from any other processes before closing them, avoiding races with other threads sharing the file descriptor table. .SH "ВОЗВРАЩАЕМОЕ ЗНАЧЕНИЕ" В случае успеха \fBclose_range\fP() возвращает 0. В случае ошибки возвращается \-1 и \fIerrno\fP устанавливается для указания ошибки. .SH ОШИБКИ .TP \fBEINVAL\fP \fIflags\fP недействителен, или \fIfirst\fP больше, чем \fIlast\fP. .P Следующее может произойти с \fBCLOSE_RANGE_UNSHARE\fP (при построении новой таблицы дескрипторов): .TP \fBEMFILE\fP The number of open file descriptors exceeds the limit specified in \fI/proc/sys/fs/nr_open\fP (see \fBproc\fP(5)). This error can occur in situations where that limit was lowered before a call to \fBclose_range\fP() where the \fBCLOSE_RANGE_UNSHARE\fP flag is specified. .TP \fBENOMEM\fP Недостаточное количество памяти ядра. .SH СТАНДАРТЫ Отсутствуют. .SH ИСТОРИЯ FreeBSD. Linux 5.9, glibc 2.34. .SH ПРИМЕЧАНИЯ .SS "Закрытие всех открытых файловых дескрипторов" .\" 278a5fbaed89dacd04e9d052f4594ffd0e0585de To avoid blindly closing file descriptors in the range of possible file descriptors, this is sometimes implemented (on Linux) by listing open file descriptors in \fI/proc/self/fd/\fP and calling \fBclose\fP(2) on each one. \fBclose_range\fP() can take care of this without requiring \fI/proc\fP and within a single system call, which provides significant performance benefits. .SS "Закрытие дескрипторов файлов перед выполнением" .\" 60997c3d45d9a67daf01c56d805ae4fec37e0bd8 Дескрипторы файлов можно безопасно закрыть с помощью .P .in +4n .EX /* нам не нужно ничего после stderr */ close_range(3, \[ti]0U, CLOSE_RANGE_UNSHARE); execve(....); .EE .in .P \fBCLOSE_RANGE_UNSHARE\fP концептуально эквивалентен .P .in +4n .EX unshare(CLONE_FILES); close_range(first, last, 0); .EE .in .P but can be more efficient: if the unshared range extends past the current maximum number of file descriptors allocated in the caller's file descriptor table (the common case when \fIlast\fP is \[ti]0U), the kernel will unshare a new file descriptor table for the caller up to \fIfirst\fP, copying as few file descriptors as possible. This avoids subsequent \fBclose\fP(2) calls entirely; the whole operation is complete once the table is unshared. .SS "Закрытие файлов при выполнении" .\" 582f1fb6b721facf04848d2ca57f34468da1813e This is particularly useful in cases where multiple pre\-\fBexec\fP setup steps risk conflicting with each other. For example, setting up a \fBseccomp\fP(2) profile can conflict with a \fBclose_range\fP() call: if the file descriptors are closed before the \fBseccomp\fP(2) profile is set up, the profile setup can't use them itself, or control their closure; if the file descriptors are closed afterwards, the seccomp profile can't block the \fBclose_range\fP() call or any fallbacks. Using \fBCLOSE_RANGE_CLOEXEC\fP avoids this: the descriptors can be marked before the \fBseccomp\fP(2) profile is set up, and the profile can control access to \fBclose_range\fP() without affecting the calling process. .SH ПРИМЕРЫ The program shown below opens the files named in its command\-line arguments, displays the list of files that it has opened (by iterating through the entries in \fI/proc/PID/fd\fP), uses \fBclose_range\fP() to close all file descriptors greater than or equal to 3, and then once more displays the process's list of open files. The following example demonstrates the use of the program: .P .in +4n .EX $ \fBtouch /tmp/a /tmp/b /tmp/c\fP $ \fB./a.out /tmp/a /tmp/b /tmp/c\fP /tmp/a opened as FD 3 /tmp/b opened as FD 4 /tmp/c opened as FD 5 /proc/self/fd/0 ==> /dev/pts/1 /proc/self/fd/1 ==> /dev/pts/1 /proc/self/fd/2 ==> /dev/pts/1 /proc/self/fd/3 ==> /tmp/a /proc/self/fd/4 ==> /tmp/b /proc/self/fd/5 ==> /tmp/b /proc/self/fd/6 ==> /proc/9005/fd ========= About to call close_range() ======= /proc/self/fd/0 ==> /dev/pts/1 /proc/self/fd/1 ==> /dev/pts/1 /proc/self/fd/2 ==> /dev/pts/1 /proc/self/fd/3 ==> /proc/9005/fd .EE .in .P Обратите внимание, что строки, показывающие имя пути \fI/proc/9005/fd\fP, являются результатом вызовов \fBopendir\fP(3). .SS "Исходный код программы" .\" SRC BEGIN (close_range.c) \& .EX #define _GNU_SOURCE #include #include #include #include #include #include #include \& /* Show the contents of the symbolic links in /proc/self/fd */ \& static void show_fds(void) { DIR *dirp; char path[PATH_MAX], target[PATH_MAX]; ssize_t len; struct dirent *dp; \& dirp = opendir("/proc/self/fd"); if (dirp == NULL) { perror("opendir"); exit(EXIT_FAILURE); } \& for (;;) { dp = readdir(dirp); if (dp == NULL) break; \& if (dp\->d_type == DT_LNK) { snprintf(path, sizeof(path), "/proc/self/fd/%s", dp\->d_name); \& len = readlink(path, target, sizeof(target)); printf("%s ==> %.*s\[rs]n", path, (int) len, target); } } \& closedir(dirp); } \& int main(int argc, char *argv[]) { int fd; \& for (size_t j = 1; j < argc; j++) { fd = open(argv[j], O_RDONLY); if (fd == \-1) { perror(argv[j]); exit(EXIT_FAILURE); } printf("%s opened as FD %d\[rs]n", argv[j], fd); } \& show_fds(); \& printf("========= About to call close_range() =======\[rs]n"); \& if (close_range(3, \[ti]0U, 0) == \-1) { perror("close_range"); exit(EXIT_FAILURE); } \& show_fds(); exit(EXIT_FAILURE); } .EE .\" SRC END .SH "СМОТРИТЕ ТАКЖЕ" \fBclose\fP(2) .PP .SH ПЕРЕВОД Русский перевод этой страницы руководства разработал(и) Azamat Hackimov , Dmitriy S. Seregin , Dmitry Bolkhovskikh , Katrin Kutepova , Yuri Kozlov , Иван Павлов и Kirill Rekhov . .PP Этот перевод является свободной программной документацией; он распространяется на условиях общедоступной лицензии GNU (GNU General Public License - GPL, .UR https://www.gnu.org/licenses/gpl-3.0.html .UE версии 3 или более поздней) в отношении авторского права, но БЕЗ КАКИХ-ЛИБО ГАРАНТИЙ. .PP Если вы обнаружите какие-либо ошибки в переводе этой страницы руководства, пожалуйста, сообщите об этом разработчику(ам) по его(их) адресу(ам) электронной почты или по адресу .MT списка рассылки русских переводчиков .ME .