Created
August 17, 2020 15:07
-
-
Save ncopa/b4f0dcb52eb992d0edda14d0fabf33a4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <errno.h> | |
#include <fcntl.h> | |
#include <limits.h> | |
#include <poll.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <time.h> | |
#include <unistd.h> | |
int close_fds(int from_fd, int max_fd) | |
{ | |
struct pollfd pfds[1024]; | |
int i, total, nclosed = 0; | |
int openmax = sysconf(_SC_OPEN_MAX); | |
if (openmax != -1 && openmax < max_fd) | |
max_fd = openmax; | |
/* init events */ | |
total = max_fd - from_fd; | |
for (i = 0; i < (total < 1024 ? total : 1024); i++) { | |
pfds[i].events = 0; | |
} | |
while (from_fd < max_fd) { | |
int nfds, r = 0; | |
total = max_fd - from_fd; | |
nfds = total < 1024 ? total : 1024; | |
for (i = 0; i < nfds; i++) | |
pfds[i].fd = from_fd + i; | |
do { | |
r = poll(pfds, nfds, 0); | |
} while (r == -1 && errno == EINTR); | |
if (r < 0) | |
return r; | |
for (i = 0; i < nfds; i++) | |
if (pfds[i].revents != POLLNVAL) { | |
nclosed++; | |
close(pfds[i].fd); | |
} | |
from_fd += nfds; | |
} | |
return nclosed; | |
} | |
int close_fds_slow(int fd, int max_fd) | |
{ | |
int openmax = sysconf(_SC_OPEN_MAX); | |
if (openmax != -1 && openmax < max_fd) | |
max_fd = openmax; | |
int total = max_fd - fd; | |
while (fd < max_fd) | |
close(fd++); | |
return total; | |
} | |
int main(int argc, char *argv[]) { | |
/* open a few fds */ | |
int fd1 = open(".", O_RDONLY); | |
int fd2 = open("/proc/self/exe", O_RDONLY); | |
int n; | |
printf("opened fds: %d and %d\n", fd1, fd2); | |
system("ls /proc/self/fd"); | |
if (argc > 1) { | |
n = close_fds_slow(3, INT_MAX); | |
} else { | |
n = close_fds(3, INT_MAX); | |
} | |
printf("Closed %i fds\n", n); | |
system("ls /proc/self/fd"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment