Skip to content

Instantly share code, notes, and snippets.

@vtols
Created October 7, 2014 13:27
Show Gist options
  • Save vtols/0900f0ea31e95e163454 to your computer and use it in GitHub Desktop.
Save vtols/0900f0ea31e95e163454 to your computer and use it in GitHub Desktop.
#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <dirent.h>
#define FD_LINK_DIR "/proc/self/fd"
#define FD_LINK FD_LINK_DIR "/%d"
#define DEV_NULL "/dev/null"
#define DEV_ZERO "/dev/zero"
#define BUFFER_SIZE 80
typedef int PIPE[2];
char *acc_types[3] = {"Write", "Read/Write", "Read"};
char *std_names[3] = {"STDIN", "STDOUT", "STDERR"};
void fd_print_info(int fd);
void fd_print_all();
int main()
{
int fd_null, fd_zero, fd_tty;
PIPE fd_pipe;
fd_print_all();
pipe(fd_pipe);
fd_print_all();
fd_null = open(DEV_NULL, O_RDONLY);
fd_zero = open(DEV_ZERO, O_RDONLY);
fd_tty = open("/dev/tty", O_RDONLY);
fd_print_all();
close(fd_tty);
dup2(fd_zero, fd_null);
dup2(STDOUT_FILENO, STDERR_FILENO);
fd_print_all();
close(fd_null);
fd_print_all();
return 0;
}
void fd_print_info(int fd)
{
char f_name_buffer[80], link_buffer[80];
int rd, acc_type, f_flags;
f_flags = fcntl(fd, F_GETFL, 0);
if (f_flags == -1) {
if (errno == EBADF)
printf("%d not open\n", fd);
else
printf("%d error\n", fd);
return;
}
if((f_flags & O_ACCMODE) == O_WRONLY)
acc_type = 0;
if ((f_flags & O_ACCMODE) == O_RDWR)
acc_type = 1;
if ((f_flags & O_ACCMODE) == O_RDONLY)
acc_type = 2;
sprintf(f_name_buffer, FD_LINK, fd);
rd = readlink(f_name_buffer, link_buffer, BUFFER_SIZE);
link_buffer[rd] = '\0';
printf("%d -> [%s], (%s) %s\n",
fd,
link_buffer,
acc_types[acc_type],
(fd < 3 ? std_names[fd] : ""));
}
void fd_print_all()
{
DIR *dirp;
struct dirent *dp;
int fd;
if ((dirp = opendir(FD_LINK_DIR)) == NULL) {
perror("Couldn't open FD dir");
return;
}
do {
if ((dp = readdir(dirp)) != NULL) {
fd = -1;
sscanf(dp->d_name, "%d", &fd);
if (fd != -1)
fd_print_info(fd);
}
} while (dp != NULL);
putchar('\n');
closedir(dirp);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment