Skip to content

Instantly share code, notes, and snippets.

@ata2001
Created January 22, 2019 22:49
Show Gist options
  • Save ata2001/e342809cd14f67d4472852c597cd72ad to your computer and use it in GitHub Desktop.
Save ata2001/e342809cd14f67d4472852c597cd72ad to your computer and use it in GitHub Desktop.
C function to close all open file descriptors on Linux
#include<stdio.h>
#include<stdlib.h>
#include<dirent.h>
int close_FDs()
{
unsigned int fd;
DIR* dp;
struct dirent* ep;
dp = opendir("/proc/self/fd");
if (dp != NULL) {
// first two entries are . and ..
readdir(dp);
readdir(dp);
while (ep = readdir(dp))
if (sscanf(ep->d_name, "%u", &fd) != EOF)
close(fd);
closedir(dp);
return 0;
} else {
return 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment