clang-tidy: add Chrome-inspired checks
[lttng-tools.git] / src / common / fd-handle.cpp
... / ...
CommitLineData
1/*
2 * Copyright (C) 2020 Jérémie Galarneau <jeremie.galarneau@efficios.com>
3 *
4 * SPDX-License-Identifier: LGPL-2.1-only
5 *
6 */
7
8#include "fd-handle.hpp"
9
10#include <common/error.hpp>
11
12#include <unistd.h>
13#include <urcu/ref.h>
14
15struct fd_handle {
16 struct urcu_ref ref;
17 int fd;
18};
19
20static void fd_handle_release(struct urcu_ref *ref)
21{
22 int ret;
23 struct fd_handle *handle = lttng::utils::container_of(ref, &fd_handle::ref);
24
25 LTTNG_ASSERT(handle->fd >= 0);
26 ret = close(handle->fd);
27 if (ret == -1) {
28 PERROR("Failed to close file descriptor of fd_handle upon release: fd = %d",
29 handle->fd);
30 }
31
32 free(handle);
33}
34
35struct fd_handle *fd_handle_create(int fd)
36{
37 struct fd_handle *handle = nullptr;
38
39 if (fd < 0) {
40 ERR("Attempted to create an fd_handle from an invalid file descriptor: fd = %d",
41 fd);
42 goto end;
43 }
44
45 handle = zmalloc<fd_handle>();
46 if (!handle) {
47 PERROR("Failed to allocate fd_handle");
48 goto end;
49 }
50
51 urcu_ref_init(&handle->ref);
52 handle->fd = fd;
53
54end:
55 return handle;
56}
57
58void fd_handle_get(struct fd_handle *handle)
59{
60 if (!handle) {
61 return;
62 }
63
64 urcu_ref_get(&handle->ref);
65}
66
67void fd_handle_put(struct fd_handle *handle)
68{
69 if (!handle) {
70 return;
71 }
72
73 urcu_ref_put(&handle->ref, fd_handle_release);
74}
75
76int fd_handle_get_fd(struct fd_handle *handle)
77{
78 LTTNG_ASSERT(handle);
79 return handle->fd;
80}
81
82struct fd_handle *fd_handle_copy(const struct fd_handle *handle)
83{
84 struct fd_handle *new_handle = nullptr;
85 const int new_fd = dup(handle->fd);
86
87 if (new_fd < 0) {
88 PERROR("Failed to duplicate file descriptor while copying fd_handle: fd = %d",
89 handle->fd);
90 goto end;
91 }
92
93 new_handle = fd_handle_create(new_fd);
94end:
95 return new_handle;
96}
This page took 0.022813 seconds and 4 git commands to generate.