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 autoClose)26 FDGuard::FDGuard(int fd, bool autoClose) : fd_(fd), autoClose_(autoClose) {}
27 
FDGuard(FDGuard && fdg)28 FDGuard::FDGuard(FDGuard &&fdg) : fd_(fdg.fd_), autoClose_(fdg.autoClose_)
29 {
30     fdg.fd_ = -1;
31 }
32 
operator =(FDGuard && fdg)33 FDGuard &FDGuard::operator=(FDGuard &&fdg)
34 {
35     if (this == &fdg) {
36         return *this;
37     }
38     this->fd_ = fdg.fd_;
39     this->autoClose_ = fdg.autoClose_;
40     fdg.fd_ = -1;
41     return *this;
42 }
43 
~FDGuard()44 FDGuard::~FDGuard()
45 {
46     if (fd_ >= 0 && fd_ <= STDERR_FILENO) {
47         HILOGI("~FDGuard, fd_ = %{public}d", fd_);
48     }
49     if (fd_ >= 0 && autoClose_) {
50         close(fd_);
51     }
52 }
53 
54 FDGuard::operator bool() const
55 {
56     return fd_ >= 0;
57 }
58 
GetFD() const59 int FDGuard::GetFD() const
60 {
61     return fd_;
62 }
63 
SetFD(int fd,bool autoClose)64 void FDGuard::SetFD(int fd, bool autoClose)
65 {
66     fd_ = fd;
67     autoClose_ = autoClose;
68 }
69 
ClearFD()70 void FDGuard::ClearFD()
71 {
72     fd_ = -1;
73 }
74 } // namespace DistributedFS
75 } // namespace OHOS
76