- int left_to_sleep = stats_interval;
- do {
- left_to_sleep = sleep(left_to_sleep);
- } while (left_to_sleep > 0 && !should_stop);
+ // Wait until the stop_fd pipe is closed, stats_interval timeout,
+ // or a spurious signal. (The latter will cause us to write stats
+ // too often, but that's okay.)
+ pollfd pfd;
+ pfd.fd = stop_fd_read;
+ pfd.events = POLLIN | POLLRDHUP;
+
+ int nfds = poll(&pfd, 1, stats_interval * 1000);
+ if (nfds == 0 || (nfds == -1 && errno == EINTR)) {
+ continue;
+ }
+ if (nfds == 1) {
+ // Should stop.
+ break;
+ }
+ if (nfds == -1) {
+ perror("poll");
+ usleep(100000);
+ continue;
+ }