#include <sys/types.h>
#include <dirent.h>
#include <sys/time.h> 
#include <unistd.h>
#include <sys/stat.h>
#include <errno.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <sys/socket.h>

#define NODEFINE
#include <u.h>
#include <libc.h>
#include <fcall.h>
#include "fd.h"

int
pm_dup(int oldfd, int newfd)
{
	int newufd;
	File *oldf, *newf;

	if((oldf = pm_lockfile(oldfd, 0)) == nil)
		return -1;
	if(newfd != -1){
		newf = pm_lockfile(newfd, 1);
		if(newf == nil){
			pm_qunlock(&oldf->lk);
			return -1;
		}
		if(dup2(oldf->ufd, newfd) < 0){
			pm_qunlock(&newf->lk);
			pm_qunlock(&oldf->lk);
			return -1;
		}
		if(newf->type != Tfree)
			pm_closefile(newf);
		newufd = newfd;
	}else{
		newufd = dup(oldf->ufd);
		if(newufd < 0){
			pm_qunlock(&oldf->lk);
			return -1;
		}
		newf = pm_allocfile(newufd);
		if(newf == nil){
			pm_qunlock(&oldf->lk);
			close(newufd);
			return -1;
		}
	}
	newf->type = oldf->type;
	newf->mode = oldf->mode;
	newf->path = oldf->path;
	newf->qid = oldf->qid;
	newf->ufd = newufd;
	pm_qunlock(&oldf->lk);
	pm_qunlock(&newf->lk);
	return newf->pmfd;
}


syntax highlighted by Code2HTML, v. 0.9.1