[libcamera-devel] [PATCH 04/30] libcamera: buffer: Add FileDecriptor to help deal with file descriptors

Niklas Söderlund niklas.soderlund at ragnatech.se
Wed Nov 27 00:35:54 CET 2019


Add a helper to make it easier to pass file descriptors around. The
helper class duplicates the fd which decouples it from the original fd
which could be closed by its owner while the new FileDescriptor remains
valid.

Signed-off-by: Niklas Söderlund <niklas.soderlund at ragnatech.se>
---
 include/libcamera/buffer.h | 12 ++++++++++++
 src/libcamera/buffer.cpp   | 40 ++++++++++++++++++++++++++++++++++++++
 2 files changed, 52 insertions(+)

diff --git a/include/libcamera/buffer.h b/include/libcamera/buffer.h
index 7302b9f32ce8c50d..33793b4ccf881eda 100644
--- a/include/libcamera/buffer.h
+++ b/include/libcamera/buffer.h
@@ -46,6 +46,18 @@ private:
 	std::vector<Plane> planes_;
 };
 
+class FileDescriptor final
+{
+public:
+	FileDescriptor(int fd);
+	~FileDescriptor();
+
+	int fd() const { return fd_; }
+
+private:
+	int fd_;
+};
+
 class Plane final
 {
 public:
diff --git a/src/libcamera/buffer.cpp b/src/libcamera/buffer.cpp
index 4acff216cafba484..0676586ae3be2a61 100644
--- a/src/libcamera/buffer.cpp
+++ b/src/libcamera/buffer.cpp
@@ -115,6 +115,46 @@ void BufferInfo::update(Status status, unsigned int sequence,
  * \return A array holding all plane information for the buffer
  */
 
+/**
+ * \class FileDescriptor
+ * \brief Life time management of a file descriptor
+ *
+ * The managed file descriptor (fd) is duplicated from the original one and
+ * is opened for the life time of the FileDescriptor object disregarding
+ * if the original one is closed.
+ */
+
+/**
+ * \brief Create a life time managed file descriptor
+ * \param[in] fd File descriptor
+ */
+FileDescriptor::FileDescriptor(int fd)
+	: fd_(-1)
+{
+	if (fd < 0)
+		return;
+
+	/* Failing to dup() a fd should not happen and is fatal. */
+	fd_ = dup(fd);
+	if (fd_ == -1) {
+		int ret = -errno;
+		LOG(Buffer, Fatal)
+			<< "Failed to dup() fd: " << strerror(-ret);
+	}
+}
+
+FileDescriptor::~FileDescriptor()
+{
+	if (fd_ != -1)
+		close(fd_);
+}
+
+/**
+ * \fn FileDescriptor::fd()
+ * \brief Retrieve the file descriptor or
+ * \return A valid file descriptor or a negative error code
+ */
+
 /**
  * \class Plane
  * \brief A memory region to store a single plane of a frame
-- 
2.24.0



More information about the libcamera-devel mailing list