blob: d14e62be959e6dcd2a4b07985367c74e8d06ffd9 [file] [log] [blame]
Brian Carlstroma97f9072013-05-14 14:44:26 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
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#ifndef SCOPED_FD_H_included
18#define SCOPED_FD_H_included
19
20#include <unistd.h>
Spencer Lowb7a25282015-04-22 17:59:56 -070021#include "JNIHelp.h" // for DISALLOW_COPY_AND_ASSIGN.
Brian Carlstroma97f9072013-05-14 14:44:26 -070022
23// A smart pointer that closes the given fd on going out of scope.
24// Use this when the fd is incidental to the purpose of your function,
25// but needs to be cleaned up on exit.
26class ScopedFd {
27public:
Dmitriy Ivanov54733ea2015-01-20 11:28:52 -080028 explicit ScopedFd(int fd) : fd_(fd) {
Brian Carlstroma97f9072013-05-14 14:44:26 -070029 }
30
31 ~ScopedFd() {
Ian Rogersa985e9e2014-06-21 22:55:27 -070032 reset();
Brian Carlstroma97f9072013-05-14 14:44:26 -070033 }
34
35 int get() const {
Dmitriy Ivanov54733ea2015-01-20 11:28:52 -080036 return fd_;
Brian Carlstroma97f9072013-05-14 14:44:26 -070037 }
38
Vladimir Markod5282122013-11-07 10:28:59 +000039 int release() __attribute__((warn_unused_result)) {
Dmitriy Ivanov54733ea2015-01-20 11:28:52 -080040 int localFd = fd_;
41 fd_ = -1;
Vladimir Markod5282122013-11-07 10:28:59 +000042 return localFd;
43 }
44
Ian Rogersa985e9e2014-06-21 22:55:27 -070045 void reset(int new_fd = -1) {
Dmitriy Ivanov54733ea2015-01-20 11:28:52 -080046 if (fd_ != -1) {
Spencer Lowb7a25282015-04-22 17:59:56 -070047 // Even if close(2) fails with EINTR, the fd will have been closed.
48 // Using TEMP_FAILURE_RETRY will either lead to EBADF or closing someone else's fd.
49 // http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
50 close(fd_);
Ian Rogersa985e9e2014-06-21 22:55:27 -070051 }
Dmitriy Ivanov54733ea2015-01-20 11:28:52 -080052 fd_ = new_fd;
Ian Rogersa985e9e2014-06-21 22:55:27 -070053 }
54
Brian Carlstroma97f9072013-05-14 14:44:26 -070055private:
Dmitriy Ivanov54733ea2015-01-20 11:28:52 -080056 int fd_;
Brian Carlstroma97f9072013-05-14 14:44:26 -070057
Ian Rogers8288dde2014-11-04 11:42:02 -080058 DISALLOW_COPY_AND_ASSIGN(ScopedFd);
Brian Carlstroma97f9072013-05-14 14:44:26 -070059};
60
61#endif // SCOPED_FD_H_included