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.
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.
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]
23 * Copyright 2008 Sun Microsystems, Inc. All rights reserved.
24 * Use is subject to license terms.
27 #pragma ident "%Z%%M% %I% %E% SMI"
29 #pragma weak _closefrom = closefrom
30 #pragma weak _fdwalk = fdwalk
42 #include <sys/resource.h>
44 /* Initial size of the open file descriptor array */
45 #define FDS_SZ (1024 * sizeof (int))
48 * Iterate over all open file descriptors, calling 'func' on each one.
49 * Terminate the iteration when 'func' returns non-zero or when all
50 * open file descriptors have been processed. Return the value of
51 * the last non-zero return from 'func' or zero.
54 fdwalk(int (*func
)(void *, int), void *cd
)
58 int max_fds
= INT_MAX
;
70 if ((dirp
= opendir("/proc/self/fd")) != NULL
) {
72 * Collect all of the open file descriptors and close
73 * the directory before calling 'func' on any of them.
75 while ((dp
= readdir64(dirp
)) != NULL
) {
76 /* skip '.', '..' and the opendir() fd */
77 if (!isdigit(dp
->d_name
[0]) ||
78 (i
= atoi(dp
->d_name
)) == dirp
->dd_fd
)
80 if (fds_sz
<= nfds
* sizeof (int)) {
81 fds
= memcpy(alloca(fds_sz
* 2), fds
, fds_sz
);
86 (void) closedir(dirp
);
89 * We could not open the /proc file descriptor directory.
90 * We have to do it the hard way.
92 if (getrlimit(RLIMIT_NOFILE
, &rl
) == 0)
93 max_fds
= (rl
.rlim_max
== RLIM_INFINITY
)?
94 INT_MAX
: rl
.rlim_max
;
95 for (i
= 0; i
< max_fds
; i
++) {
96 if (fcntl(i
, F_GETFD
) < 0)
98 if (fds_sz
<= nfds
* sizeof (int)) {
99 fds
= memcpy(alloca(fds_sz
* 2), fds
, fds_sz
);
107 * Restore the original value of errno so that
108 * the caller sees only the value of errno set
109 * by the callback function.
114 * Perform the callbacks on all of the open files.
116 for (i
= 0; i
< nfds
; i
++)
117 if ((rv
= func(cd
, fds
[i
])) != 0)
124 * Call-back function for closefrom(), below.
127 void_close(void *lowp
, int fd
)
129 if (fd
>= *(int *)lowp
)
135 * Close all open file descriptors greater than or equal to lowfd.
140 int low
= (lowfd
< 0)? 0 : lowfd
;
143 * Close lowfd right away as a hedge against failing
144 * to open the /proc file descriptor directory due
145 * all file descriptors being currently used up.
148 (void) fdwalk(void_close
, &low
);