1 /*
2 * Copyright (c) 2021 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "fd_guard.h"
17
18 #include <unistd.h>
19
20 #include "../log.h"
21
22 namespace OHOS {
23 namespace DistributedFS {
FDGuard(int fd)24 FDGuard::FDGuard(int fd) : fd_(fd) {}
25
FDGuard(int fd,bool autoDestruct)26 FDGuard::FDGuard(int fd, bool autoDestruct) : fd_(fd), autoDestruct_(autoDestruct) {}
27
FDGuard(const FDGuard & fdg)28 FDGuard::FDGuard(const FDGuard& fdg) : fd_(fdg.fd_), autoDestruct_(fdg.autoDestruct_) {}
29
operator =(const FDGuard & fdg)30 FDGuard& FDGuard::operator=(const FDGuard& fdg)
31 {
32 if (this == &fdg) {
33 return *this;
34 }
35 this->fd_ = fdg.fd_;
36 this->autoDestruct_ = fdg.autoDestruct_;
37 return *this;
38 }
39
~FDGuard()40 FDGuard::~FDGuard()
41 {
42 if (fd_ >= 0 && fd_ <= STDERR_FILENO) {
43 HILOGI("~FDGuard, fd_ = %{public}d", fd_);
44 }
45 if (fd_ >= 0 && autoDestruct_) {
46 close(fd_);
47 }
48 }
49
GetFD() const50 int FDGuard::GetFD() const
51 {
52 return fd_;
53 }
54
SetFD(int fd,bool autoDestruct)55 void FDGuard::SetFD(int fd, bool autoDestruct)
56 {
57 fd_ = fd;
58 autoDestruct_ = autoDestruct;
59 }
60
operator =(int fd)61 void FDGuard::operator=(int fd)
62 {
63 fd_ = fd;
64 }
65
ClearFD()66 void FDGuard::ClearFD()
67 {
68 fd_ = -1;
69 }
70 } // namespace DistributedFS
71 } // namespace OHOS
72