Skip to content

Instantly share code, notes, and snippets.

@emersion
Created October 3, 2017 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emersion/cd54a1694644cb2ab1488cd8dd265a4f to your computer and use it in GitHub Desktop.
Save emersion/cd54a1694644cb2ab1488cd8dd265a4f to your computer and use it in GitHub Desktop.
// Source: https://oroboro.com/file-handle-leaks-server/
#define _POSIX_C_SOURCE 200112L
#include <unistd.h>
#include <fcntl.h>
int maxfd = sysconf(_SC_OPEN_MAX);
for (int fd = 3; fd < maxfd; fd++) {
int fd_flags = fcntl(fd, F_GETFD);
if (fd_flags < 0) {
continue;
}
int fl_flags = fcntl(fd, F_GETFL);
if (fl_flags < 0) {
continue;
}
char buf[256];
char path[256];
sprintf(path, "/proc/self/fd/%d", fd);
memset(&buf[0], 0, 256);
ssize_t s = readlink(path, &buf[0], 256);
if (s == -1)
{
printf("%d (%s): not available ", fd, path);
continue;
}
printf("%d (%s): ", fd, buf);
if (fd_flags & FD_CLOEXEC) printf("cloexec ");
// file status
if (fl_flags & O_APPEND ) printf("append ");
if (fl_flags & O_NONBLOCK) printf("nonblock ");
// acc mode
if (fl_flags & O_RDONLY ) printf("read-only ");
if (fl_flags & O_RDWR ) printf("read-write ");
if (fl_flags & O_WRONLY ) printf("write-only ");
if (fl_flags & O_DSYNC ) printf("dsync ");
if (fl_flags & O_RSYNC ) printf("rsync ");
if (fl_flags & O_SYNC ) printf("sync ");
struct flock fl;
fl.l_type = F_WRLCK;
fl.l_whence = 0;
fl.l_start = 0;
fl.l_len = 0;
fcntl(fd, F_GETLK, &fl);
if (fl.l_type != F_UNLCK)
{
if (fl.l_type == F_WRLCK)
printf("write-locked");
else
printf("read-locked");
printf("(pid: %d) ", fl.l_pid);
}
printf("\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment