File: unique_fd.h

package info (click to toggle)
fakeroot-ng 0.18-4.1
  • links: PTS
  • area: main
  • in suites: bullseye
  • size: 1,076 kB
  • sloc: cpp: 4,595; sh: 3,831; ansic: 1,581; makefile: 28
file content (66 lines) | stat: -rw-r--r-- 1,331 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#ifndef UNIQUE_FD_H
#define UNIQUE_FD_H

#include <sys/file.h>
#include <unistd.h>
#include "exceptions.h"

struct unique_fd {
    int _fd;

    unique_fd( const unique_fd &rhs )=delete;
    unique_fd & operator=( const unique_fd &rhs )=delete;
public:
    explicit unique_fd( int fd=-1, const char *exception_message=nullptr ) : _fd( fd>=0 ? fd : -1 )
    {
        if( _fd<0 && exception_message )
            throw errno_exception( exception_message );
    }

    // Movers
    explicit unique_fd( unique_fd &&rhs )
    {
        _fd=rhs._fd;
        rhs._fd=-1;
    }
    unique_fd & operator=( unique_fd &&rhs )
    {
        _fd=rhs._fd;
        rhs._fd=-1;

        return *this;
    }

    // Destructor
    ~unique_fd()
    {
        if( _fd>=0 )
            if( close(_fd)<0 )
                throw errno_exception( "Close failed" );
    }

    int get() const { return _fd; }
    int release()
    {
        int ret=get();
        _fd=-1;
        return ret;
    }

    operator bool() const { return _fd>=0; }

    // File related operations
    bool flock( int operation )
    {
        if( ::flock( get(), operation )<0 ) {
            if( errno==EWOULDBLOCK )
                return false;

            throw errno_exception( "flock failed" );
        }
        
        return true;
    }
};

#endif // UNIQUE_FD_H