summaryrefslogtreecommitdiff
path: root/lib/libpthread/uthread/uthread_closefrom.c
blob: 20d332f92a7e0627b1e1dbdd143022a557a4aeab (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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/* $OpenBSD: uthread_closefrom.c,v 1.1 2004/01/15 22:22:11 marc Exp $ */

/* PUBLIC DOMAIN: No Rights Reserved. Marco S Hyman <marc@snafu.org> */

#include <sys/stat.h>

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

#include "pthread_private.h"

/*
 * Reset the non-blocking flag if necessary.   Remove the fd table entry
 * for the given fd.
 */
static void
_close_flags(int fd)
{
	struct stat sb;
	int flags;

	if (_FD_LOCK(fd, FD_RDWR, NULL) == 0) {
		if ((_thread_sys_fstat(fd, &sb) == 0) &&
		    ((S_ISREG(sb.st_mode) || S_ISCHR(sb.st_mode)) &&
		     (_thread_fd_table[fd]->flags & O_NONBLOCK) == 0)) {
			/* Get the current flags: */
			flags = _thread_sys_fcntl(fd, F_GETFL, NULL);
			/* Clear the nonblocking file descriptor flag: */
			_thread_sys_fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
		}
		_thread_fd_table_remove(fd);
	}
}

int
closefrom(int fd)
{
	int ret;
	int safe_fd;
	int lock_fd;

	_thread_enter_cancellation_point();
	
	if (fd < 0 || fd >= _thread_dtablesize) {
		errno = EBADF;
		ret = -1;
	} else {
		safe_fd = _thread_kern_pipe[0] > _thread_kern_pipe[1] ?
			_thread_kern_pipe[0] : _thread_kern_pipe[1];

		/*
		 * close individual files until we get past the pipe
		 * fds.  Attempting to close a pipe fd is a no-op.
		 */
		for (safe_fd++; fd < safe_fd; fd++)
			close(fd);

		/* Reset flags and clean up the fd table for fds to close */
		for (lock_fd = fd; lock_fd < _thread_dtablesize; lock_fd++)
			if (_thread_fd_table[lock_fd] != NULL)
				_close_flags(lock_fd);

		/* Now let the system do its thing */
		ret = _thread_sys_closefrom(fd);
	}

	_thread_leave_cancellation_point();

	return ret;

}