io/FileDescriptor: add Duplicate() returning UniqueFileDescriptor

This commit is contained in:
Max Kellermann 2022-06-24 14:21:59 +02:00 committed by Max Kellermann
parent 5140eaa5e7
commit 899eaa3307
2 changed files with 17 additions and 0 deletions

View File

@ -28,6 +28,7 @@
*/ */
#include "FileDescriptor.hxx" #include "FileDescriptor.hxx"
#include "UniqueFileDescriptor.hxx"
#include "system/Error.hxx" #include "system/Error.hxx"
#include <cassert> #include <cassert>
@ -234,6 +235,12 @@ FileDescriptor::DisableCloseOnExec() noexcept
fcntl(fd, F_SETFD, old_flags & ~FD_CLOEXEC); fcntl(fd, F_SETFD, old_flags & ~FD_CLOEXEC);
} }
UniqueFileDescriptor
FileDescriptor::Duplicate() const noexcept
{
return UniqueFileDescriptor{::dup(Get())};
}
bool bool
FileDescriptor::CheckDuplicate(FileDescriptor new_fd) noexcept FileDescriptor::CheckDuplicate(FileDescriptor new_fd) noexcept
{ {

View File

@ -44,6 +44,8 @@
#include <wchar.h> #include <wchar.h>
#endif #endif
class UniqueFileDescriptor;
/** /**
* An OO wrapper for a UNIX file descriptor. * An OO wrapper for a UNIX file descriptor.
* *
@ -176,6 +178,14 @@ public:
*/ */
void DisableCloseOnExec() noexcept; void DisableCloseOnExec() noexcept;
/**
* Duplicate this file descriptor.
*
* @return the new file descriptor or UniqueFileDescriptor{}
* on error
*/
UniqueFileDescriptor Duplicate() const noexcept;
/** /**
* Duplicate the file descriptor onto the given file descriptor. * Duplicate the file descriptor onto the given file descriptor.
*/ */