/* Unix-like dup() and dup2() functions.  They depend on a special version
   of "close()" to clean up properly.
*/
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>

int dup2(int od, int nd)
{
    struct _dev *op, *np;

    if (nd < 0 || nd >= _numdev ||
	od < 0 || od >= _numdev || !((op = &(_devtab[od]))->fd)) {
	errno = EBADF;
	return(-1);
    }
    
    if ((np = &(_devtab[nd]))->fd) close(nd);
    op->mode |= 0x2000;
    *np = *op;		/* Structure copy */
    return (0);
}

int dup(int od)
{
    struct _dev *dt = _devtab;
    int nd;

    for (nd = 0; nd < _numdev; nd++) {
	if (!dt[nd].fd) {
	    if (!dup2(od,nd)) return(nd);
	}
    }
    errno = EMFILE;
    return(-1);
}
