forked from Kistler-Group/sdbus-cpp
refactor: minor UnixFd cleanups (#376)
* chore: Use std::exchange in UnixFd This was suggested in code review for #376 . * fix: Protect against UnixFd self-assignment While self-assignment is rare, it is expected to be safe. Add a check to prevent putting the object in an invalid state. * fix: Improve hygiene around dup system call - Don't try to call dup on a negative value. - Check dup return code and throw if it fails, rather than returning an empty UnixFd object. * chore: Move UnixFd::close to Types.cpp Minor convenience for applications: unistd.h doesn't have to be included in the public header. --------- Co-authored-by: David Reiss <dreiss@meta.com>
This commit is contained in:
co-authored by
David Reiss
parent
f50e4676fe
commit
6e348f3910
@@ -29,6 +29,9 @@
|
||||
#include "MessageUtils.h"
|
||||
#include SDBUS_HEADER
|
||||
#include <cassert>
|
||||
#include <cerrno>
|
||||
#include <system_error>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace sdbus {
|
||||
|
||||
@@ -64,4 +67,27 @@ bool Variant::isEmpty() const
|
||||
return msg_.isEmpty();
|
||||
}
|
||||
|
||||
void UnixFd::close()
|
||||
{
|
||||
if (fd_ >= 0)
|
||||
{
|
||||
::close(fd_);
|
||||
}
|
||||
}
|
||||
|
||||
int UnixFd::checkedDup(int fd)
|
||||
{
|
||||
if (fd < 0)
|
||||
{
|
||||
return fd;
|
||||
}
|
||||
|
||||
int ret = ::dup(fd);
|
||||
if (ret < 0)
|
||||
{
|
||||
throw std::system_error(errno, std::generic_category(), "dup failed");
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user