From 2940072ad2e4a074da9b091fce89adc50e29c6e0 Mon Sep 17 00:00:00 2001 From: Karen Arutyunov Date: Tue, 8 Nov 2016 16:09:37 +0300 Subject: Add fddup() --- butl/fdstream | 11 +++++++++-- butl/fdstream.cxx | 20 +++++++++++++++++--- 2 files changed, 26 insertions(+), 5 deletions(-) (limited to 'butl') diff --git a/butl/fdstream b/butl/fdstream index 289d925..d3dbef7 100644 --- a/butl/fdstream +++ b/butl/fdstream @@ -52,8 +52,9 @@ namespace butl void reset (int fd = -1) noexcept; - // Close an open file descriptor. Throw ios::failure on failure. The object - // become unopened whenever the exception is thrown or not. + // Close an open file descriptor. Throw ios::failure on the underlying OS + // error. Reset the descriptor to -1 whenever the exception is thrown or + // not. // void close (); @@ -498,6 +499,12 @@ namespace butl permissions::rg | permissions::wg | permissions::ro | permissions::wo); + // Duplicate an open file descriptor. Throw ios::failure on the underlying + // OS error. + // + LIBBUTL_EXPORT auto_fd + fddup (int fd); + // Set the translation mode for the file descriptor. Return the previous // mode on success, throw ios::failure otherwise. // diff --git a/butl/fdstream.cxx b/butl/fdstream.cxx index 102ad66..16801ed 100644 --- a/butl/fdstream.cxx +++ b/butl/fdstream.cxx @@ -6,14 +6,14 @@ #ifndef _WIN32 # include // open(), O_*, fcntl() -# include // close(), read(), write(), lseek(), ssize_t, +# include // close(), read(), write(), lseek(), dup(), ssize_t, // STD*_FILENO # include // writev(), iovec # include // S_I* # include // off_t #else # include // _close(), _read(), _write(), _setmode(), _sopen(), - // _lseek() + // _lseek(), _dup() # include // _SH_DENYNO # include // _fileno(), stdin, stdout, stderr # include // _O_* @@ -87,7 +87,6 @@ namespace butl } } - // fdbuf // fdbuf:: @@ -737,6 +736,21 @@ namespace butl return auto_fd (fd); } + auto_fd + fddup (int fd) + { +#ifndef _WIN32 + int nfd (dup (fd)); +#else + int nfd (_dup (fd)); +#endif + + if (nfd == -1) + throw_ios_failure (errno); + + return auto_fd (nfd); + } + #ifndef _WIN32 bool -- cgit v1.1