a9c7be4a938ab86aa44d3c6316c3ccd8a04e6537
[lttng-tools.git] / src / common / fd-handle.c
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 <unistd.h>
9 #include <urcu/ref.h>
10
11 #include "fd-handle.h"
12 #include <common/error.h>
13
14 struct fd_handle {
15 struct urcu_ref ref;
16 int fd;
17 };
18
19 static void fd_handle_release(struct urcu_ref *ref)
20 {
21 int ret;
22 struct fd_handle *handle = container_of(ref, struct fd_handle, ref);
23
24 assert(handle->fd >= 0);
25 ret = close(handle->fd);
26 if (ret == -1) {
27 PERROR("Failed to close file descriptor of fd_handle upon release: fd = %d",
28 handle->fd);
29 }
30
31 free(handle);
32 }
33
34 LTTNG_HIDDEN
35 struct fd_handle *fd_handle_create(int fd)
36 {
37 struct fd_handle *handle = NULL;
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(sizeof(*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
54 end:
55 return handle;
56 }
57
58 LTTNG_HIDDEN
59 void fd_handle_get(struct fd_handle *handle)
60 {
61 assert(handle);
62 urcu_ref_get(&handle->ref);
63 }
64
65 LTTNG_HIDDEN
66 void fd_handle_put(struct fd_handle *handle)
67 {
68 assert(handle);
69 urcu_ref_put(&handle->ref, fd_handle_release);
70 }
71
72 LTTNG_HIDDEN
73 int fd_handle_get_fd(struct fd_handle *handle)
74 {
75 assert(handle);
76 return handle->fd;
77 }
78
79 LTTNG_HIDDEN
80 struct fd_handle *fd_handle_copy(const struct fd_handle *handle)
81 {
82 struct fd_handle *new_handle = NULL;
83 const int new_fd = dup(handle->fd);
84
85 if (new_fd < 0) {
86 PERROR("Failed to duplicate file descriptor while copying fd_handle: fd = %d", handle->fd);
87 goto end;
88 }
89
90 new_handle = fd_handle_create(new_fd);
91 end:
92 return new_handle;
93 }
This page took 0.030657 seconds and 4 git commands to generate.