1 /*
2  * Copyright (c) 2024 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 #ifndef OHOS_ABILITY_RUNTIME_FD_GUARD_H
17 #define OHOS_ABILITY_RUNTIME_FD_GUARD_H
18 
19 #include <cstdint>
20 #include <unistd.h>
21 
22 namespace OHOS {
23 namespace AAFwk {
24 class FdGuard {
25 public:
26     FdGuard() = default;
FdGuard(int32_t fd)27     explicit FdGuard(int32_t fd) : fd_(fd) {}
~FdGuard()28     ~FdGuard()
29     {
30         if (fd_ > -1) {
31             close(fd_);
32         }
33     }
34     FdGuard(const FdGuard &) = delete;
FdGuard(FdGuard && other)35     FdGuard(FdGuard &&other) : fd_(other.fd_)
36     {
37         other.fd_ = -1;
38     }
39     void operator=(const FdGuard &) = delete;
40     FdGuard &operator=(FdGuard &&other)
41     {
42         if (fd_ > -1) {
43             close(fd_);
44         }
45         fd_ = other.fd_;
46         other.fd_ = -1;
47         return *this;
48     }
49 
GetFd()50     int32_t GetFd() const
51     {
52         return fd_;
53     }
54 
Release()55     int32_t Release()
56     {
57         auto ret = fd_;
58         fd_ = -1;
59         return ret;
60     }
61 
Reset()62     void Reset()
63     {
64         if (fd_ > -1) {
65             close(fd_);
66         }
67         fd_ = -1;
68     }
69 
70 private:
71     int32_t fd_ = -1;
72 };
73 } // AAFwk
74 } // OHOS
75 #endif // OHOS_ABILITY_RUNTIME_FD_GUARD_H