1/*
2 * Copyright 2002 Niels Provos <provos@citi.umich.edu>
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 */
25
26
27/* -*- Mode: C++; tab-width: 8; c-basic-offset: 2; indent-tabs-mode: nil; -*- */
28
29#ifndef RR_SCOPED_FD_H_
30#define RR_SCOPED_FD_H_
31
32#include <fcntl.h>
33#include <sys/stat.h>
34#include <sys/types.h>
35#include <unistd.h>
36
37/**
38 * RAII helper to open a file and then close the fd when the helper
39 * goes out of scope.
40 */
41class ScopedFd {
42public:
43 ScopedFd() : fd(-1) {}
44 ScopedFd(int fd) : fd(fd) {}
45 ScopedFd(const char* pathname, int flags, mode_t mode = 0)
46 : fd(open(pathname, flags, mode)) {}
47 ScopedFd(ScopedFd&& other) : fd(other.fd) { other.fd = -1; }
48 ~ScopedFd() { close(); }
49
50 ScopedFd& operator=(ScopedFd&& other) {
51 close();
52 fd = other.fd;
53 other.fd = -1;
54 return *this;
55 }
56
57 operator int() const { return get(); }
58 int get() const { return fd; }
59 int extract() {
60 int result = fd;
61 fd = -1;
62 return result;
63 }
64
65 bool is_open() { return fd >= 0; }
66 void close() {
67 if (fd >= 0) {
68 ::close(fd);
69 }
70 fd = -1;
71 }
72
73private:
74 int fd;
75};
76
77#endif // RR_SCOPED_FD_H
78