file_descriptor_posix.h 2.4 KB

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