aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/Common/EventFD.cpp
blob: af50ca62271e3f9287f2e9ba34ced63293e060bf (plain) (blame)
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
67
#if defined(OS_LINUX)

#include <Common/EventFD.h>
#include <Common/Exception.h>
#include <base/defines.h>
#include <sys/eventfd.h>
#include <unistd.h>

namespace DB
{

namespace ErrorCodes
{
    extern const int CANNOT_PIPE;
    extern const int CANNOT_READ_FROM_SOCKET;
    extern const int CANNOT_WRITE_TO_SOCKET;
}

EventFD::EventFD()
{
    fd = eventfd(0 /* initval */, 0 /* flags */);
    if (fd == -1)
        throwFromErrno("Cannot create eventfd", ErrorCodes::CANNOT_PIPE);
}

uint64_t EventFD::read() const
{
    uint64_t buf = 0;
    while (-1 == ::read(fd, &buf, sizeof(buf)))
    {
        if (errno == EAGAIN)
            break;

        if (errno != EINTR)
            throwFromErrno("Cannot read from eventfd", ErrorCodes::CANNOT_READ_FROM_SOCKET);
    }

    return buf;
}

bool EventFD::write(uint64_t increase) const
{
    while (-1 == ::write(fd, &increase, sizeof(increase)))
    {
        if (errno == EAGAIN)
            return false;

        if (errno != EINTR)
            throwFromErrno("Cannot write to eventfd", ErrorCodes::CANNOT_WRITE_TO_SOCKET);
    }

    return true;
}

EventFD::~EventFD()
{
    if (fd != -1)
    {
        int err = close(fd);
        chassert(!err || errno == EINTR);
    }
}

}

#endif