closefromtest.c revision 180718
155682Smarkm/*
2233294Sstas * Copyright (c) 2006 Darren Tucker
3233294Sstas *
4233294Sstas * Permission to use, copy, modify, and distribute this software for any
555682Smarkm * purpose with or without fee is hereby granted, provided that the above
6233294Sstas * copyright notice and this permission notice appear in all copies.
7233294Sstas *
8233294Sstas * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
955682Smarkm * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10233294Sstas * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11233294Sstas * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
1255682Smarkm * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13233294Sstas * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14233294Sstas * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15233294Sstas */
1655682Smarkm
17233294Sstas#include <sys/types.h>
18233294Sstas#include <sys/stat.h>
19233294Sstas
2055682Smarkm#include <fcntl.h>
21233294Sstas#include <stdio.h>
22233294Sstas#include <stdlib.h>
23233294Sstas#include <unistd.h>
24233294Sstas
25233294Sstas#define NUM_OPENS 10
26233294Sstas
27233294Sstasvoid
28233294Sstasfail(char *msg)
29233294Sstas{
30233294Sstas	fprintf(stderr, "closefrom: %s\n", msg);
31233294Sstas	exit(1);
3255682Smarkm}
3355682Smarkm
3455682Smarkmint
3555682Smarkmmain(void)
3655682Smarkm{
3755682Smarkm	int i, max, fds[NUM_OPENS];
3855682Smarkm	char buf[512];
3955682Smarkm
4055682Smarkm	for (i = 0; i < NUM_OPENS; i++)
4155682Smarkm		if ((fds[i] = open("/dev/null", "r")) == -1)
4255682Smarkm			exit(0);	/* can't test */
4355682Smarkm	max = i - 1;
4455682Smarkm
4555682Smarkm	/* should close last fd only */
46120945Snectar	closefrom(fds[max]);
47120945Snectar	if (close(fds[max]) != -1)
48120945Snectar		fail("failed to close highest fd");
49120945Snectar
50120945Snectar	/* make sure we can still use remaining descriptors */
5155682Smarkm	for (i = 0; i < max; i++)
5255682Smarkm		if (read(fds[i], buf, sizeof(buf)) == -1)
5355682Smarkm			fail("closed descriptors it should not have");
5455682Smarkm
5555682Smarkm	/* should close all fds */
5655682Smarkm	closefrom(fds[0]);
5755682Smarkm	for (i = 0; i < NUM_OPENS; i++)
5855682Smarkm		if (close(fds[i]) != -1)
5955682Smarkm			fail("failed to close from lowest fd");
60120945Snectar}
61120945Snectar