xdwonder911
xdwonder911

Reputation: 13

Printing file descriptors from PID in C on Linux

So I have to print names of all the file descriptors of a certain PID. I know how to access it through the terminal navigating to proc/[pid]/fd, but all I get are colored numbers. I can get their name by writing ls -l.


My Question is how can I print these names in C. I tried using stat, but I couldn't get it to work, then I used g_dir_open. It didn't work aswell since i couldn't properly include glib.h ("galloca.h not found in glib.h").

Thank you very much in advance, Oh and please keep in mind that I'm a complete fool when it comes to linux.

Upvotes: 1

Views: 1523

Answers (1)

tijko
tijko

Reputation: 8292

By using a combination of readdir and readlink you can get the absolute paths of all your descriptors. In this sample I use an arbitary pid, you can set it as a commandline argument or anyway you are calling the function.

#include <stdio.h>
#include <fcntl.h>
#include <limits.h>
#include <string.h>
#include <stdlib.h>
#include <dirent.h>
#include <unistd.h>


int main(int argc, char *argv[])
{
    char *path = "/proc/3525/fd";
    DIR *fd_dir = opendir(path);

    if (!fd_dir) {
        perror("opendir");
        return 0;
    }

    struct dirent *cdir;
    size_t fd_path_len = strlen(path) + 10;
    char *fd_path = malloc(sizeof(char) * fd_path_len);
    char *buf = malloc(sizeof(char) * PATH_MAX + 1);

    while ((cdir = readdir(fd_dir))) {
        if (strcmp(cdir->d_name, ".") == 0 ||
            strcmp(cdir->d_name, "..") == 0)
            continue;
        snprintf(fd_path, fd_path_len - 1, "%s/%s", path, cdir->d_name);
        printf("Checking: %s\n", fd_path);
        ssize_t link_size = readlink(fd_path, buf, PATH_MAX);
        if (link_size < 0)
            perror("readlink");
        else {
            buf[link_size] = '\0';
            printf("%s\n", buf);
        }
        memset(fd_path, '0', fd_path_len);
    }

    closedir(fd_dir);
    free(fd_path);
    free(buf);

    return 0;
}

Upvotes: 3

Related Questions