xref: /aosp_15_r20/external/cronet/base/file_descriptor_posix.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2006-2009 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_FILE_DESCRIPTOR_POSIX_H_
6 #define BASE_FILE_DESCRIPTOR_POSIX_H_
7 
8 #include "base/base_export.h"
9 #include "base/files/scoped_file.h"
10 
11 namespace base {
12 
13 class File;
14 
15 constexpr int kInvalidFd = -1;
16 
17 // -----------------------------------------------------------------------------
18 // We introduct a special structure for file descriptors in order that we are
19 // able to use template specialisation to special-case their handling.
20 //
21 // IMPORTANT: This is primarily intended for use when sending file descriptors
22 // over IPC. Even if |auto_close| is true, base::FileDescriptor does NOT close()
23 // |fd| when going out of scope. Instead, a consumer of a base::FileDescriptor
24 // must invoke close() on |fd| if |auto_close| is true.
25 //
26 // In the case of IPC, the IPC subsystem knows to close() |fd| after sending
27 // a message that contains a base::FileDescriptor if auto_close == true. On the
28 // other end, the receiver must make sure to close() |fd| after it has finished
29 // processing the IPC message. See the IPC::ParamTraits<> specialization in
30 // ipc/ipc_message_utils.h for all the details.
31 // -----------------------------------------------------------------------------
32 struct BASE_EXPORT FileDescriptor {
33   FileDescriptor();
34   FileDescriptor(int ifd, bool iauto_close);
35   explicit FileDescriptor(File file);
36   explicit FileDescriptor(ScopedFD fd);
37 
38   bool operator==(const FileDescriptor& other) const;
39   bool operator!=(const FileDescriptor& other) const;
40 
41   // A comparison operator so that we can use these as keys in a std::map.
42   bool operator<(const FileDescriptor& other) const;
43 
44   int fd = kInvalidFd;
45 
46   // If true, this file descriptor should be closed after it has been used. For
47   // example an IPC system might interpret this flag as indicating that the
48   // file descriptor it has been given should be closed after use.
49   bool auto_close = false;
50 };
51 
52 }  // namespace base
53 
54 #endif  // BASE_FILE_DESCRIPTOR_POSIX_H_
55