Fcitx
unixfd.h
Go to the documentation of this file.
1 /*
2  * SPDX-FileCopyrightText: 2016-2017 CSSlayer <wengxt@gmail.com>
3  *
4  * SPDX-License-Identifier: LGPL-2.1-or-later
5  *
6  */
7 #ifndef _FCITX_UTILS_UNIXFD_H_
8 #define _FCITX_UTILS_UNIXFD_H_
9 
10 /// \addtogroup FcitxUtils
11 /// \{
12 /// \file
13 /// \brief Utility class to handle unix file decriptor.
14 
15 #include <fcitx-utils/fcitxutils_export.h>
16 #include <fcitx-utils/log.h>
17 #include <fcitx-utils/macros.h>
18 
19 namespace fcitx {
20 
21 /// \brief Class wrap around the unix fd.
22 class FCITXUTILS_EXPORT UnixFD {
23 public:
24  /// \brief Create an empty UnixFD.
25  UnixFD() noexcept;
26 
27  /// \brief Create a UnixFD by using dup.
28  explicit UnixFD(int fd);
29  /**
30  * Create UnixFD with dup, with give parameter to dup.
31  *
32  * @param fd file descriptor to duplicate.
33  * @param min minimum file descriptor number
34  * @since 5.1.6
35  */
36  explicit UnixFD(int fd, int min);
37  UnixFD(const UnixFD &other) = delete;
38  FCITX_DECLARE_MOVE(UnixFD);
39  ~UnixFD() noexcept;
40 
41  /// \brief Create a UnixFD by owning the fd.
42  static UnixFD own(int fd) {
43  UnixFD unixFD;
44  unixFD.give(fd);
45  return unixFD;
46  }
47 
48  /// \brief Check if fd is not empty.
49  bool isValid() const noexcept;
50 
51  /// \brief Set a new FD.
52  ///
53  /// if fd is -1, reset it. Otherwise use dup to make copy.
54  void set(int fd);
55 
56  /**
57  * Set a new FD.
58  *
59  * if fd is -1, reset it. Otherwise use dup to make copy.
60  *
61  * @param fd file descriptor to duplicate.
62  * @param min minimum file descriptor number
63  * @since 5.1.6
64  */
65  void set(int fd, int min);
66 
67  /// \brief Clear the FD and close it.
68  void reset() noexcept;
69 
70  /// \brief Get the internal fd and release the ownership.
71  int release() noexcept;
72 
73  /// \brief Get the internal fd.
74  int fd() const noexcept;
75 
76  /// \brief Set a new FD and transfer the ownership to UnixFD.
77  void give(int fd) noexcept;
78 
79 private:
80  int fd_ = -1;
81 };
82 
83 static inline LogMessageBuilder &operator<<(LogMessageBuilder &builder,
84  const UnixFD &fd) {
85  builder << "UnixFD(fd=" << fd.fd() << ")";
86  return builder;
87 }
88 } // namespace fcitx
89 
90 #endif // _FCITX_UTILS_UNIXFD_H_
Class wrap around the unix fd.
Definition: unixfd.h:22
Definition: action.cpp:17
int fd() const noexcept
Get the internal fd.
Definition: unixfd.cpp:41
static UnixFD own(int fd)
Create a UnixFD by owning the fd.
Definition: unixfd.h:42
void give(int fd) noexcept
Set a new FD and transfer the ownership to UnixFD.
Definition: unixfd.cpp:43
Log utilities.