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
#include "lix/libutil/monitor-fd.hh"
#include "lix/libutil/error.hh"
#include "lix/libutil/file-descriptor.hh"
#include <atomic>
#include <future>
#include <gtest/gtest.h>
#include <sys/socket.h>

using namespace std::literals::chrono_literals;

namespace nix {

TEST(MonitorFdHup, works)
{
    int socks[2];
    int rv = socketpair(AF_UNIX, SOCK_STREAM, 0, socks);
    if (rv) {
        throw SysError("socketpair");
    }
    auto sock1 = AutoCloseFD{socks[0]};
    auto sock2 = AutoCloseFD{socks[1]};

    std::promise<void> called;

    MonitorFdHup monitor(sock1.get(), [&called]() { called.set_value(); });

    sock2.close();

    // 10 seconds should certainly do it.
    auto status = called.get_future().wait_for(10s);
    ASSERT_EQ(status, std::future_status::ready);
}

// Ensures that it also works with pipes.
TEST(MonitorFdHup, works_with_pipes)
{
    Pipe pipes{};
    pipes.create();
    std::promise<void> called;

    MonitorFdHup monitor(pipes.readSide.get(), [&called]() { called.set_value(); });

    pipes.writeSide.close();

    // 10 seconds should certainly do it.
    auto status = called.get_future().wait_for(10s);
    ASSERT_EQ(status, std::future_status::ready);
}

// Ensures that destroying the MonitorFdHup causes it to actually go away.
TEST(MonitorFdHup, destroys_safely)
{
    int socks[2];
    int rv = socketpair(AF_UNIX, SOCK_STREAM, 0, socks);
    if (rv) {
        throw SysError("socketpair");
    }
    auto sock1 = AutoCloseFD{socks[0]};
    auto sock2 = AutoCloseFD{socks[1]};

    {
        MonitorFdHup monitor(sock1.get(), []() { abort(); });
    }
}

}