//go:build linux || darwin package containment import ( "time" "golang.org/x/sys/unix" ) // zeroTimeoutTries caps the calls a zero-timeout poll makes when every one // is interrupted. Such a poll takes microseconds, so a few tries ride out an // odd signal, while a steady stream of signals cannot keep the caller (for // example recovery) spinning; it gets the EINTR and fails closed. const zeroTimeoutTries = 8 // pollFD is unix.Poll that does not report a signal as a failure. func pollFD(fds []unix.PollFd, timeout time.Duration) (int, error) { return pollRetry(fds, timeout, unix.Poll) } // pollRetry polls again when a signal interrupts the call. A timed poll // retries only for the time left of the original timeout and then reports a // timeout (0, nil). A zero timeout has no time to measure, so it makes at // most zeroTimeoutTries calls and then returns the EINTR. func pollRetry(fds []unix.PollFd, timeout time.Duration, poll func([]unix.PollFd, int) (int, error)) (int, error) { deadline := time.Now().Add(timeout) for tries := 1; ; tries++ { n, e := poll(fds, int(timeout.Milliseconds())) if e != unix.EINTR { return n, e } if timeout > 0 { if timeout = time.Until(deadline); timeout <= 0 { return 0, nil } } else if tries >= zeroTimeoutTries { return 0, e } } }