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

#include <thread>
#include <atomic>

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

namespace nix {


class MonitorFdHup
{
private:
    std::thread thread;
    std::atomic_bool quit;

public:
    MonitorFdHup(int fd)
    {
        quit = false;
        thread = std::thread([&]() {
            /* Wait indefinitely until a POLLHUP occurs. */
            struct pollfd fds[1];
            fds[0].fd = fd;
            fds[0].events = 0;
            if (poll(fds, 1, -1) == -1) {
                if (errno != EINTR) abort(); // can't happen
                assert(quit);
                return; // destructor is asking us to exit
            }
            fprintf(stderr, "GOT: %d\n", fds[0].revents);
            assert(fds[0].revents & POLLHUP);
            /* We got POLLHUP, so send an INT signal to the main thread. */
            kill(getpid(), SIGINT);
        });
    };

    ~MonitorFdHup()
    {
        quit = true;
        pthread_kill(thread.native_handle(), SIGINT);
        thread.join();
    }
};


}