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

#include "rsxnt.h"

int __dup(int fd)
{
    EMXPROCESS *p = _rsxnt_get_process_ptr();
    int newfd;
    HANDLE h;

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

    if ((newfd = _rsxnt_get_new_file(p)) < 0)
        return _rsxnt_errno(EMFILE);

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