Add fd_handle interface
[lttng-tools.git] / src / common / fd-handle.c
CommitLineData
dd1bac00
JG
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
14struct fd_handle {
15 struct urcu_ref ref;
16 int fd;
17};
18
19static 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
34LTTNG_HIDDEN
35struct 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
54end:
55 return handle;
56}
57
58LTTNG_HIDDEN
59void fd_handle_get(struct fd_handle *handle)
60{
61 assert(handle);
62 urcu_ref_get(&handle->ref);
63}
64
65LTTNG_HIDDEN
66void fd_handle_put(struct fd_handle *handle)
67{
68 assert(handle);
69 urcu_ref_put(&handle->ref, fd_handle_release);
70}
71
72LTTNG_HIDDEN
73int fd_handle_get_fd(struct fd_handle *handle)
74{
75 assert(handle);
76 return handle->fd;
77}
78
79LTTNG_HIDDEN
80struct 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);
91end:
92 return new_handle;
93}
This page took 0.02553 seconds and 4 git commands to generate.