1 /* 2 * Copyright (c) 2017 Facebook, Inc. 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 17 #pragma once 18 19 #include <unistd.h> 20 21 namespace ebpf { 22 23 /// FileDesc is a helper class for managing open file descriptors. Copy is 24 /// disallowed (call dup instead), and cleanup happens automatically. 25 class FileDesc { 26 public: fd_(fd)27 explicit FileDesc(int fd = -1) : fd_(fd) {} FileDesc(FileDesc && that)28 FileDesc(FileDesc &&that) : fd_(-1) { *this = std::move(that); } 29 FileDesc(const FileDesc &that) = delete; 30 ~FileDesc()31 ~FileDesc() { 32 if (fd_ >= 0) 33 ::close(fd_); 34 } 35 36 FileDesc &operator=(int fd) { 37 if (fd_ >= 0) 38 ::close(fd_); 39 fd_ = fd; 40 return *this; 41 } 42 FileDesc &operator=(FileDesc &&that) { 43 if (fd_ >= 0) 44 ::close(fd_); 45 fd_ = that.fd_; 46 that.fd_ = -1; 47 return *this; 48 } 49 FileDesc &operator=(const FileDesc &that) = delete; 50 dup()51 FileDesc dup() const { 52 int dup_fd = ::dup(fd_); 53 return FileDesc(dup_fd); 54 } 55 56 operator int() { return fd_; } 57 operator int() const { return fd_; } 58 59 private: 60 int fd_; 61 }; 62 63 } // namespace ebpf 64