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

Laurent Pinchart laurent.pinchart at ideasonboard.com
Mon Dec 9 19:12:41 CET 2019


Hello Niklas,

On Wed, Nov 27, 2019 at 12:35:54AM +0100, Niklas Söderlund wrote:
> 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 ++++++++++++++++++++++++++++++++++++++

I missed this, you should move this class to file_descriptor.{h,cpp} as
it may be useful beyond buffers.

>  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

-- 
Regards,

Laurent Pinchart


More information about the libcamera-devel mailing list