/* waitpid.c (rsxnt) -- Copyright (c) 1996-1998 Rainer Schnitker */

#include "rsxnt.h"
#include <string.h>

#ifdef EMX_SYS_LIB /* dynamic link via ctordtor in ptrace() */
extern WAIT_DEBUG _func_rsxnt_wait_debuggee = NULL;
#endif

int __waitpid(int pid, int *status, int request)
{
    EMXPROCESS *p = _rsxnt_get_process_ptr();
    int i, tmppid;
    DWORD dwExit;
    DWORD rc;

    if (pid == -1)
        return __wait(status);

    if (p->debuggee.pid == pid && p->debuggee.status)
#ifndef EMX_SYS_LIB
        return _rsxnt_wait_debuggee(status);
#else
        if (_func_rsxnt_wait_debuggee)
            return (*_func_rsxnt_wait_debuggee)(status);
#endif

    for (i = 0; i < MAX_CHILD; i++)
        if (p->childs[i].pid == pid)
            break;
    if (i >= MAX_CHILD)
        return _rsxnt_errno(ECHILD);

    if (request == 1) {
        rc = WaitForSingleObject(p->childs[i].hProcess, 1);
        if (rc == WAIT_FAILED)
            return _rsxnt_errno(ECHILD);
        else if (rc == WAIT_TIMEOUT) {
            *status = 0;
            return 0;
        }
    }
    else {
        rc = WaitForSingleObject(p->childs[i].hProcess, INFINITE);
        if (rc == WAIT_FAILED)
            return _rsxnt_errno(ECHILD);
    }

    GetExitCodeProcess(p->childs[i].hProcess, &dwExit);
    CloseHandle (p->childs[i].hProcess);
    *status = dwExit << 8;

    tmppid = p->childs[i].pid;
    memset (&(p->childs[i]), 0, sizeof(struct child));
    return tmppid;
}
