xref: /titanic_41/usr/src/lib/libbc/libc/sys/common/dup2.c (revision 40cb5e5daa7b80bb70fcf8dadfb20f9281566331)
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, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 1990 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 <syscall.h>
32 #include <sys/errno.h>
33 
34 #define OPEN_MAX 20		/* Taken from SVR4 limits.h */
35 
36 int dup2(fildes, fildes2)
37 int fildes,		/* file descriptor to be duplicated */
38     fildes2;		/* desired file descriptor */
39 {
40       int     tmperrno;       /* local work area */
41       register int open_max;  /* max open files */
42       extern  int     errno;  /* system error indicator */
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 }
80