1 /* 2 * Copyright (C) 2024 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 #include "host/commands/process_sandboxer/unique_fd.h" 17 18 #include <unistd.h> 19 20 #include <absl/log/log.h> 21 22 namespace cuttlefish { 23 namespace process_sandboxer { 24 UniqueFd(int fd)25UniqueFd::UniqueFd(int fd) : fd_(fd) {} 26 UniqueFd(UniqueFd && other)27UniqueFd::UniqueFd(UniqueFd&& other) { std::swap(fd_, other.fd_); } 28 ~UniqueFd()29UniqueFd::~UniqueFd() { Close(); } 30 operator =(UniqueFd && other)31UniqueFd& UniqueFd::operator=(UniqueFd&& other) { 32 Close(); 33 std::swap(fd_, other.fd_); 34 return *this; 35 } 36 Get() const37int UniqueFd::Get() const { return fd_; } 38 Release()39int UniqueFd::Release() { 40 int ret = -1; 41 std::swap(ret, fd_); 42 return ret; 43 } 44 Reset(int fd)45void UniqueFd::Reset(int fd) { 46 Close(); 47 fd_ = fd; 48 } 49 Close()50void UniqueFd::Close() { 51 if (fd_ > 0 && close(fd_) < 0) { 52 PLOG(ERROR) << "Failed to close fd " << fd_; 53 } 54 fd_ = -1; 55 } 56 57 } // namespace process_sandboxer 58 } // namespace cuttlefish 59