summaryrefslogtreecommitdiffstats
path: root/gnu/usr.bin/cvs/lib/dup2.c
blob: 0bd3aca82db68c048dacfd41d6510249802d0d4c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/*
	dup2 -- 7th Edition UNIX system call emulation for UNIX System V

	last edit:	11-Feb-1987	D A Gwyn
*/

#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 */
	(void) close( newfd );		/* in case newfd is open */
	/* (may have just clobbered the original errno value) */

	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 */
}
OpenPOWER on IntegriCloud