xref: /titanic_50/usr/src/lib/libbc/libc/sys/common/dup2.c (revision c77a61a72b5ecdc507d6cf104142edd371a16c84)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include <fcntl.h>
30 #include <unistd.h>
31 #include <sys/syscall.h>
32 #include <errno.h>
33 
34 #define	OPEN_MAX	20		/* Taken from SVR4 limits.h */
35 
36 int
37 dup2(
38 	int fildes,		/* file descriptor to be duplicated */
39 	int fildes2)		/* desired file descriptor */
40 {
41 	int	tmperrno;	/* local work area */
42 	int	open_max;	/* max open files */
43 	int	ret;		/* return value */
44 	int	fds;		/* duplicate files descriptor */
45 
46 	if ((open_max = ulimit(4, 0)) < 0)
47 		open_max = OPEN_MAX;	/* take a guess */
48 
49 	/* Be sure fildes is valid and open */
50 	if (fcntl(fildes, F_GETFL, 0) == -1) {
51 		errno = EBADF;
52 		return (-1);
53 	}
54 
55 	/* Be sure fildes2 is in valid range */
56 	if (fildes2 < 0 || fildes2 >= open_max) {
57 		errno = EBADF;
58 		return (-1);
59 	}
60 
61 	/* Check if file descriptors are equal */
62 	if (fildes == fildes2) {
63 		/* open and equal so no dup necessary */
64 		return (fildes2);
65 	}
66 	/* Close in case it was open for another file */
67 	/* Must save and restore errno in case file was not open */
68 	tmperrno = errno;
69 	close(fildes2);
70 	errno = tmperrno;
71 
72 	/* Do the dup */
73 	if ((ret = fcntl(fildes, F_DUPFD, fildes2)) != -1) {
74 		if ((fds = fd_get(fildes)) != -1)
75 			fd_add(fildes2, fds);
76 	}
77 	return (ret);
78 }
79