• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
2 // -*- mode: C++ -*-
3 //
4 // Copyright 2022 Google LLC
5 //
6 // Licensed under the Apache License v2.0 with LLVM Exceptions (the
7 // "License"); you may not use this file except in compliance with the
8 // License.  You may obtain a copy of the License at
9 //
10 //     https://llvm.org/LICENSE.txt
11 //
12 // Unless required by applicable law or agreed to in writing, software
13 // distributed under the License is distributed on an "AS IS" BASIS,
14 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 // See the License for the specific language governing permissions and
16 // limitations under the License.
17 //
18 // Author: Aleksei Vetrov
19 // Author: Matthias Maennich
20 
21 #include "file_descriptor.h"
22 
23 #include <fcntl.h>
24 #include <unistd.h>
25 
26 #include <cerrno>
27 #include <exception>
28 
29 #include "error.h"
30 
31 namespace stg {
32 
FileDescriptor(const char * filename,int flags,mode_t mode)33 FileDescriptor::FileDescriptor(const char* filename, int flags, mode_t mode)
34     : fd_(open(filename, flags, mode)) {
35   if (fd_ < 0) {
36     Die() << "open failed: " << Error(errno);
37   }
38 }
39 
~FileDescriptor()40 FileDescriptor::~FileDescriptor() noexcept(false) {
41   // If we're unwinding, ignore any close failure.
42   if (fd_ >= 0 && close(fd_) != 0 && std::uncaught_exceptions() == 0) {
43     Die() << "close failed: " << Error(errno);
44   }
45   fd_ = -1;
46 }
47 
48 
Value() const49 int FileDescriptor::Value() const {
50   Check(fd_ >= 0) << "FileDescriptor was not initialized";
51   return fd_;
52 }
53 
54 }  // namespace stg
55