.\" -*- coding: UTF-8 -*- .\" This manpage is Copyright (C) 1992 Drew Eckhardt; .\" and Copyright (C) 1993 Michael Haardt, Ian Jackson. .\" and Copyright (C) 2005, 2008 Michael Kerrisk .\" and Copyright (C) 2014 Michael Kerrisk .\" .\" SPDX-License-Identifier: Linux-man-pages-copyleft .\" .\" Modified 1993-07-21, Rik Faith .\" Modified 1994-08-21, Michael Chastain : .\" Fixed typos. .\" Modified 1997-01-31, Eric S. Raymond .\" Modified 2002-09-28, aeb .\" 2009-01-12, mtk, reordered text in DESCRIPTION and added some .\" details for dup2(). .\" 2008-10-09, mtk: add description of dup3() .\" .\"******************************************************************* .\" .\" This file was generated with po4a. Translate the source file. .\" .\"******************************************************************* .TH dup 2 "2 мая 2024 г." "Справочные страницы Linux 6.9.1" .SH НАИМЕНОВАНИЕ dup, dup2, dup3 \- создать дубликат файлового дескриптора .SH БИБЛИОТЕКА Стандартная библиотека языка C (\fIlibc\fP, \fI\-lc\fP) .SH ОБЗОР .nf \fB#include \fP .P \fBint dup(int \fP\fIoldfd\fP\fB);\fP \fBint dup2(int \fP\fIoldfd\fP\fB, int \fP\fInewfd\fP\fB);\fP .P \fB#define _GNU_SOURCE\fP /* См. feature_test_macros(7) */ \fB#include \fP /* Определение констант \fBO_*\fP */ \fB#include \fP .P \fBint dup3(int \fP\fIoldfd\fP\fB, int \fP\fInewfd\fP\fB, int \fP\fIflags\fP\fB);\fP .fi .SH ОПИСАНИЕ The \fBdup\fP() system call allocates a new file descriptor that refers to the same open file description as the descriptor \fIoldfd\fP. (For an explanation of open file descriptions, see \fBopen\fP(2).) The new file descriptor number is guaranteed to be the lowest\-numbered file descriptor that was unused in the calling process. .P After a successful return, the old and new file descriptors may be used interchangeably. Since the two file descriptors refer to the same open file description, they share file offset and file status flags; for example, if the file offset is modified by using \fBlseek\fP(2) on one of the file descriptors, the offset is also changed for the other file descriptor. .P .\" Эти два файловых дескриптора имеют различные флаги дескриптора файла (флаг close\-on\-exec). Флаг close\-on\-exec (\fBFD_CLOEXEC\fP; см. \fBfcntl\fP(2)) у копии дескриптора сбрасывается. .SS dup2() The \fBdup2\fP() system call performs the same task as \fBdup\fP(), but instead of using the lowest\-numbered unused file descriptor, it uses the file descriptor number specified in \fInewfd\fP. In other words, the file descriptor \fInewfd\fP is adjusted so that it now refers to the same open file description as \fIoldfd\fP. .P If the file descriptor \fInewfd\fP was previously open, it is closed before being reused; the close is performed silently (i.e., any errors during the close are not reported by \fBdup2\fP()). .P Шаги по закрытию и повторному использованию файлового дескриптора \fInewfd\fP выполняются \fIатомарно\fP. Это важно, так как попытка реализовать подобное с помощью \fBclose\fP(2) и \fBdup\fP() привело бы к состязательности, в силу чего \fInewfd\fP мог быть задействован повторно между этими двумя шагами. Такое повторное использование может произойти, из\-за прерывания основной программы обработчиком сигналов, который выделяет файловый дескриптор, или из\-за параллельной нити, выделяющей файловый дескриптор. .P Также заметим следующее: .IP \[bu] 3 Если \fIoldfd\fP является некорректным файловым дескриптором, то вызов завершается с ошибкой, а \fInewfd\fP не закрывается. .IP \[bu] .\" Если \fIoldfd\fP является корректным файловым дескриптором, а номер \fInewfd\fP совпадает с \fIoldfd\fP, то \fBdup2\fP() не делает ничего и возвращает значение \fInewfd\fP. .SS dup3() \fBdup3\fP() похож на \fBdup2\fP(). Отличия заключаются в следующем: .IP \[bu] 3 Вызывающий может принудительно установить флаг close\-on\-exec flag у нового файлового дескриптора, указав \fBO_CLOEXEC\fP в \fIflags\fP. Зачем это может быть нужно смотрите в \fBopen\fP(2). .IP \[bu] .\" Ulrich Drepper, LKML, 2008-10-09: .\" We deliberately decided on this change. Otherwise, what is the .\" result of dup3(fd, fd, O_CLOEXEC)? Если \fIoldfd\fP равно \fInewfd\fP, то \fBdup3\fP() выдает ошибку \fBEINVAL\fP. .SH "ВОЗВРАЩАЕМОЕ ЗНАЧЕНИЕ" On success, these system calls return the new file descriptor. On error, \-1 is returned, and \fIerrno\fP is set to indicate the error. .SH ОШИБКИ .TP \fBEBADF\fP Значение \fIoldfd\fP не является открытым файловым дескриптором. .TP \fBEBADF\fP Значение \fInewfd\fP находится вне допустимого диапазона файловых дескрипторов (смотрите описание \fBRLIMIT_NOFILE\fP в \fBgetrlimit\fP(2)). .TP \fBEBUSY\fP (только в Linux) Может случиться в \fBdup2\fP() или \fBdup3\fP() при возникновении состязательности вызовов \fBopen\fP(2) и \fBdup\fP(). .TP \fBEINTR\fP Вызов \fBdup2\fP() или \fBdup3\fP() был прерван каким\-либо сигналом. Смотрите \fBsignal\fP(7). .TP \fBEINVAL\fP (\fBdup3\fP()) \fIflags\fP содержит некорректное значение. .TP \fBEINVAL\fP (\fBdup3\fP()) \fIoldfd\fP было равно \fInewfd\fP. .TP \fBEMFILE\fP Было достигнуто ограничение по количеству открытых файловых дескрипторов на процесс (смотрите описание \fBRLIMIT_NOFILE\fP в \fBgetrlimit\fP(2)). .SH СТАНДАРТЫ .TP \fBdup\fP() .TQ \fBdup2\fP() POSIX.1\-2008. .TP \fBdup3\fP() Linux. .SH ИСТОРИЯ .TP \fBdup\fP() .TQ \fBdup2\fP() .\" SVr4 documents additional .\" EINTR and ENOLINK error conditions. POSIX.1 adds EINTR. .\" The EBUSY return is Linux-specific. POSIX.1\-2001, SVr4, 4.3BSD. .TP \fBdup3\fP() Linux 2.6.27, glibc 2.9. .SH ПРИМЕЧАНИЯ Ошибка, которую возвращает \fBdup2\fP(), отличается от той, что возвращает \fBfcntl(\fP…, \fBF_DUPFD\fP, …\fB)\fP, когда \fInewfd\fP находится вне допустимых пределов. На некоторых системах \fBdup2\fP() также иногда возвращает \fBEINVAL\fP — как \fBF_DUPFD\fP. .P If \fInewfd\fP was open, any errors that would have been reported at \fBclose\fP(2) time are lost. If this is of concern, then\[em]unless the program is single\-threaded and does not allocate file descriptors in signal handlers\[em]the correct approach is \fInot\fP to close \fInewfd\fP before calling \fBdup2\fP(), because of the race condition described above. Instead, code something like the following could be used: .P .in +4n .EX /* Obtain a duplicate of \[aq]newfd\[aq] that can subsequently be used to check for close() errors; an EBADF error means that \[aq]newfd\[aq] was not open. */ \& tmpfd = dup(newfd); if (tmpfd == \-1 && errno != EBADF) { /* Handle unexpected dup() error. */ } \& /* Atomically duplicate \[aq]oldfd\[aq] on \[aq]newfd\[aq]. */ \& if (dup2(oldfd, newfd) == \-1) { /* Handle dup2() error. */ } \& /* Now check for close() errors on the file originally referred to by \[aq]newfd\[aq]. */ \& if (tmpfd != \-1) { if (close(tmpfd) == \-1) { /* Handle errors from close. */ } } .EE .in .SH "СМОТРИТЕ ТАКЖЕ" \fBclose\fP(2), \fBfcntl\fP(2), \fBopen\fP(2), \fBpidfd_getfd\fP(2) .PP .SH ПЕРЕВОД Русский перевод этой страницы руководства разработал(и) 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 .