
from __future__ import absolute_import
from __future__ import division

import os
import signal

_trackedPids = set()
_registered = False


def autoReapPID(pid):
    if not _registered:
        raise RuntimeError("zombiereaper is not registered for SIGCHLD")
    _trackedPids.add(pid)
    _tryReap(pid)


def _tryReap(pid):
        try:
            pid, rv = os.waitpid(pid, os.WNOHANG)
            if pid != 0:
                _trackedPids.discard(pid)
        except OSError:
            _trackedPids.discard(pid)


def _zombieReaper(signum, frame):
    for pid in _trackedPids.copy():
        _tryReap(pid)


def registerSignalHandler():
    global _registered
    signal.signal(signal.SIGCHLD, _zombieReaper)
    _registered = True


def unregisterSignalHandler():
    global _registered
    signal.signal(signal.SIGCHLD, signal.SIG_DFL)
    _registered = False
