/* dup2.c (rsxnt) -- Copyright (c) 1996-1997 Rainer Schnitker */

#include "rsxnt.h"

int __dup2(int oldfd, int newfd)
{
    HANDLE h;
    EMXPROCESS *p = _rsxnt_get_process_ptr();

    if (oldfd >= N_FILES || oldfd < 0
        || p->file[oldfd].f_handle == INVALID_HANDLE_VALUE)
        return _rsxnt_errno(EBADF);

    if (oldfd == newfd)
        return newfd;
    if (newfd >= N_FILES || newfd < 0)
        return _rsxnt_errno(EBADF);

    __close (newfd);

    if (DuplicateHandle(p->hProcess, p->file[oldfd].f_handle,
            p->hProcess, &h, 0, TRUE, DUPLICATE_SAME_ACCESS) == FALSE) {
        return _rsxnt_get_last_errno();
     } else {
        p->file[newfd].f_handle = h;
        p->file[newfd].f_mode = p->file[oldfd].f_mode;
        _rsxnt_check_console_handle(p, newfd);
        return newfd;
    }
}
