dup2() system call

Dan Bernstein brnstnd at kramden.acf.nyu.edu
Thu Apr 25 21:04:12 AEST 1991


Someone complained that Doug's dup2() failed if the original file
descriptor was closed. Is this version right, or are further changes
necessary?

---Dan

/*
	dup2 -- 7th Edition UNIX system call emulation for UNIX System V
		11-Feb-1987	D A Gwyn
		25-Apr-1991	DJB - keep newfd open if oldfd is bad
*/

#include	<errno.h>
#include	<fcntl.h>

extern int	close(), fcntl();

int
dup2( oldfd, newfd )
	int		oldfd;		/* already-open file descriptor */
	int		newfd;		/* desired duplicate descriptor */
{
	register int	ret;		/* for fcntl() return value */
	register int	save;		/* for saving entry errno */

	if ( oldfd == newfd )
		return oldfd;		/* be careful not to close() */

	save = errno;			/* save entry errno */
	ret = fcntl( oldfd, F_GETFL, 0 );	/* don't close if oldfd bad */
	/* (may have just clobbered the original errno value) */
	if ( ret >= 0 ) {

		(void) close( newfd );		/* in case newfd is open */

		ret = fcntl( oldfd, F_DUPFD, newfd );	/* dupe it */
	}

	if ( ret >= 0 )
		errno = save;		/* restore entry errno */
	else				/* fcntl() returned error */
		if ( errno == EINVAL )
			errno = EBADF;	/* we think of everything */

	return ret;			/* return file descriptor */
}



More information about the Comp.unix.programmer mailing list