xref: /freebsd/lib/libutil++/freebsd__fd_up.3 (revision 159503125826bc2d3b988921e7e85735ee09ad46)
1.\"
2.\" SPDX-License-Identifier: BSD-2-Clause
3.\"
4.\" Copyright (c) 2025 Chelsio Communications, Inc.
5.\" Written by: John Baldwin <jhb@FreeBSD.org>
6.\"
7.Dd July 31, 2025
8.Dt FREEBSD::STRINGF 3
9.Os
10.Sh NAME
11.Nm freebsd::fd_up
12.Nd own a file descriptor
13.Sh LIBRARY
14.Lb libutil++
15.Sh SYNOPSIS
16.In libutil++.hh
17.Pp
18.Vt class freebsd::fd_up
19{
20.Bd -ragged -offset indent
21.Fn fd_up
22.Fn fd_up "int fd"
23.Fn fd_up "fd_up &&other"
24.Fn ~fd_up
25.Ft int
26.Fn get
27.Ft int
28.Fn release
29.Ft void
30.Fn reset "int newfd = -1"
31.Ft "fd_up &"
32.Fn operator= "fd_up &&other"
33.Ft "fd_up &"
34.Fn operator= "int fd"
35.Fn "explicit operator bool"
36.Fn "operator int"
37.Ed
38};
39.Sh DESCRIPTION
40Each instance of this class owns a file descriptor.
41This class is patterned on std::unique_ptr,
42but instead of owning a pointer to an object,
43this class owns a file descriptor.
44The currently-owned file descriptor is disposed by invoking
45.Xr close 2
46when an instance of this class is destroyed.
47The currently-owned file descriptor is also disposed if it is replaced by the
48.Fn reset
49method or assignment operators.
50.Pp
51The
52.Fn get
53method returns the current file descriptor value while retaining ownership.
54.Pp
55The
56.Fn release
57method relinquishes ownership of the current file descriptor and returns the
58value of the previously-owned file descriptor.
59.Pp
60The explicit
61.Vt bool
62conversion operator permits testing the validity of an object.
63The operator returns true if the instance owns a valid file descriptor.
64.Pp
65The implicit
66.Vt int
67conversion operator permits passing an instance of this class directly as
68an argument to existing functions which expect a file descriptor.
69.Sh EXAMPLES
70.Bd -literal -offset indent
71freebsd::fd_up fd(open("/dev/null", O_RDWR));
72if (!fd)
73	err(1, "open");
74write(fd, "test", 4);
75// `fd' is implicitly closed on destruction
76.Ed
77.Sh SEE ALSO
78.Xr close 2
79