about summary refs log tree commit diff
path: root/src/libutil/monitor-fd.hh
blob: e0ec66c018030c1a3a458d3167fb444b08063c05 (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
#pragma once

#include <thread>
#include <atomic>

#include <cstdlib>
#include <poll.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>

namespace nix {


class MonitorFdHup
{
private:
    std::thread thread;

public:
    MonitorFdHup(int fd)
    {
        thread = std::thread([fd]() {
            /* Wait indefinitely until a POLLHUP occurs. */
            struct pollfd fds[1];
            fds[0].fd = fd;
            fds[0].events = 0;
            if (poll(fds, 1, -1) == -1) abort(); // can't happen
            assert(fds[0].revents & POLLHUP);
            triggerInterrupt();
        });
    };

    ~MonitorFdHup()
    {
        pthread_cancel(thread.native_handle());
        thread.join();
    }
};


}