def wait_pid(pid, timeout=None):
def check_timeout(delay):<EOL><INDENT>if timeout is not None:<EOL><INDENT>if time.time() >= stop_at:<EOL><INDENT>raise TimeoutExpired(pid)<EOL><DEDENT><DEDENT>time.sleep(delay)<EOL>return min(delay * <NUM_LIT:2>, <NUM_LIT>)<EOL><DEDENT>if timeout is not None:<EOL><INDENT>waitcall = lambda: os.waitpid(pid, os.WNOHANG)<EOL>stop_at = time.time() + timeout<EOL><DEDENT>else:<EOL><INDENT>waitcall = lambda: os.waitpid(pid, <NUM_LIT:0>)<EOL><DEDENT>delay = <NUM_LIT><EOL>while <NUM_LIT:1>:<EOL><INDENT>try:<EOL><INDENT>retpid, status = waitcall()<EOL><DEDENT>except OSError:<EOL><INDENT>err = sys.exc_info()[<NUM_LIT:1>]<EOL>if err.errno == errno.EINTR:<EOL><INDENT>delay = check_timeout(delay)<EOL>continue<EOL><DEDENT>elif err.errno == errno.ECHILD:<EOL><INDENT>while <NUM_LIT:1>:<EOL><INDENT>if pid_exists(pid):<EOL><INDENT>delay = check_timeout(delay)<EOL><DEDENT>else:<EOL><INDENT>return<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if retpid == <NUM_LIT:0>:<EOL><INDENT>delay = check_timeout(delay)<EOL>continue<EOL><DEDENT>if os.WIFSIGNALED(status):<EOL><INDENT>return os.WTERMSIG(status)<EOL><DEDENT>elif os.WIFEXITED(status):<EOL><INDENT>return os.WEXITSTATUS(status)<EOL><DEDENT>else:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT><DEDENT><DEDENT>
Wait for process with pid 'pid' to terminate and return its
    exit status code as an integer.

    If pid is not a children of os.getpid() (current process) just
    waits until the process disappears and return None.

    If pid does not exist at all return None immediately.

    Raise TimeoutExpired on timeout expired.