1142425Snectar/* 2142425Snectar * Copyright (c) 2006 Darren Tucker 3142425Snectar * 4142425Snectar * Permission to use, copy, modify, and distribute this software for any 5142425Snectar * purpose with or without fee is hereby granted, provided that the above 6142425Snectar * copyright notice and this permission notice appear in all copies. 7142425Snectar * 8142425Snectar * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 9142425Snectar * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 10142425Snectar * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 11142425Snectar * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 12142425Snectar * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 13142425Snectar * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 14142425Snectar * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 15142425Snectar */ 16142425Snectar 17142425Snectar#include <sys/types.h> 18142425Snectar#include <sys/stat.h> 19142425Snectar 20142425Snectar#include <fcntl.h> 21142425Snectar#include <stdio.h> 22142425Snectar#include <stdlib.h> 23142425Snectar#include <unistd.h> 24142425Snectar 25142425Snectar#define NUM_OPENS 10 26142425Snectar 27142425Snectarint closefrom(int); 28142425Snectar 29142425Snectarvoid 30142425Snectarfail(char *msg) 31142425Snectar{ 32142425Snectar fprintf(stderr, "closefrom: %s\n", msg); 33142425Snectar exit(1); 34142425Snectar} 35142425Snectar 36142425Snectarint 37142425Snectarmain(void) 38142425Snectar{ 39142425Snectar int i, max, fds[NUM_OPENS]; 40238405Sjkim char buf[512]; 41142425Snectar 42142425Snectar for (i = 0; i < NUM_OPENS; i++) 43142425Snectar if ((fds[i] = open("/dev/null", O_RDONLY)) == -1) 44142425Snectar exit(0); /* can't test */ 45142425Snectar max = i - 1; 46142425Snectar 47142425Snectar /* should close last fd only */ 48142425Snectar closefrom(fds[max]); 49142425Snectar if (close(fds[max]) != -1) 50142425Snectar fail("failed to close highest fd"); 51142425Snectar 52142425Snectar /* make sure we can still use remaining descriptors */ 53160814Ssimon for (i = 0; i < max; i++) 54160814Ssimon if (read(fds[i], buf, sizeof(buf)) == -1) 55142425Snectar fail("closed descriptors it should not have"); 56142425Snectar 57142425Snectar /* should close all fds */ 58142425Snectar closefrom(fds[0]); 59142425Snectar for (i = 0; i < NUM_OPENS; i++) 60142425Snectar if (close(fds[i]) != -1) 61142425Snectar fail("failed to close from lowest fd"); 62142425Snectar return 0; 63142425Snectar} 64142425Snectar