system: make sys_object::duplicate public

It's useful to clone std handles when creating streams to write/read to
standard streams. As the stream we give handle to assumes the handle
ownership, it'd close the std handles in stream destructor.

Signed-off-by: Simon Rozman <simon@rozman.si>
This commit is contained in:
Simon Rozman 2024-04-17 13:58:59 +02:00
parent 525645b43b
commit 1f242823d0

View File

@ -100,14 +100,14 @@ namespace stdex
public: public:
sys_object(_In_opt_ sys_handle h = invalid_handle) : m_h(h) {} sys_object(_In_opt_ sys_handle h = invalid_handle) : m_h(h) {}
sys_object(_In_ const sys_object& other) : m_h(other.m_h != invalid_handle ? duplicate(other.m_h, false) : invalid_handle) {} sys_object(_In_ const sys_object& other) : m_h(other.m_h != invalid_handle ? duplicate(other.m_h) : invalid_handle) {}
sys_object& operator =(_In_ const sys_object& other) sys_object& operator =(_In_ const sys_object& other)
{ {
if (this != std::addressof(other)) { if (this != std::addressof(other)) {
if (m_h != invalid_handle) if (m_h != invalid_handle)
close(m_h); close(m_h);
m_h = other.m_h != invalid_handle ? duplicate(other.m_h, false) : invalid_handle; m_h = other.m_h != invalid_handle ? duplicate(other.m_h) : invalid_handle;
} }
return *this; return *this;
} }
@ -155,6 +155,25 @@ namespace stdex
/// ///
sys_handle get() const noexcept { return m_h; } sys_handle get() const noexcept { return m_h; }
///
/// Duplicates given object
///
static sys_handle duplicate(_In_ sys_handle h, _In_ bool inherit = false)
{
sys_handle h_new;
#ifdef _WIN32
HANDLE process = GetCurrentProcess();
if (DuplicateHandle(process, h, process, &h_new, 0, inherit, DUPLICATE_SAME_ACCESS))
return h_new;
throw std::system_error(GetLastError(), std::system_category(), "DuplicateHandle failed");
#else
_Unreferenced_(inherit);
if ((h_new = dup(h)) >= 0)
return h_new;
throw std::system_error(errno, std::system_category(), "dup failed");
#endif
}
protected: protected:
/// ///
/// Closes object /// Closes object
@ -172,25 +191,6 @@ namespace stdex
#endif #endif
} }
///
/// Duplicates given object
///
static sys_handle duplicate(_In_ sys_handle h, _In_ bool inherit)
{
sys_handle h_new;
#ifdef _WIN32
HANDLE process = GetCurrentProcess();
if (DuplicateHandle(process, h, process, &h_new, 0, inherit, DUPLICATE_SAME_ACCESS))
return h_new;
throw std::system_error(GetLastError(), std::system_category(), "DuplicateHandle failed");
#else
_Unreferenced_(inherit);
if ((h_new = dup(h)) >= 0)
return h_new;
throw std::system_error(errno, std::system_category(), "dup failed");
#endif
}
protected: protected:
sys_handle m_h; sys_handle m_h;
}; };